Sobes.tech
Senior

func merge(chs ...<-chan int) <-chan int { ... } package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go func(n int) { defer wg.Done() fmt.Println(i) }(i) } wg.Wait() }

sobes.tech AI

Answer from AI

The provided code contains a classic closure mistake in goroutines:

for i := 0; i < 5; i++ {
    wg.Add(1)
    go func(n int) {
        defer wg.Done()
        fmt.Println(i) // Error: here the external variable i is used
    }(i)
}

Although the parameter n is passed to the function, inside it the external variable i is used. By the time the goroutine executes, the value of i may already be 5, so all goroutines will print 5.

The correct approach is to use the parameter n inside the goroutine:

for i := 0; i < 5; i++ {
    wg.Add(1)
    go func(n int) {
        defer wg.Done()
        fmt.Println(n) // Use the parameter n
    }(i)
}

This guarantees that each goroutine will print its own value of i at the moment of launch.

func merge(chs ...<-chan int) <-chan int { ... }… - sobes.tech