When writing concurrent code in Go, it's important to understand the behavior of anonymous functions. In this example, we explore a scenario where a for loop and an anonymous function produce unexpected output.
func main() { var wg sync.WaitGroup for i := 1; i <= 5; i++ { wg.Add(1) go func() { fmt.Println(i) time.Sleep(time.Second * 1) wg.Done() }() } wg.Wait() }
Running this code surprisingly outputs "6, 6, 6, 6, 6" instead of the expected sequence "2, 4, 1, 5, 3." This is because the for loop continues to update the variable i after the goroutines have been launched.
The anonymous function in the code above is a closure. Closures capture the variables used in the function's body at the time they're created. In this case, the variable i is captured when the goroutine is launched. However, the loop continues to update i after the goroutine has started.
Since the loop does not terminate until i is greater than 5, i is 6 when the goroutines finally execute. Therefore, each goroutine prints the value of i that was captured in the closure, which is 6 in this case. The expected output is only observed when the variable i is passed as an argument to the anonymous function, effectively creating a copy of the value at the time of the call.
The above is the detailed content of Why Does My Go Concurrency Example Print \'6, 6, 6, 6, 6\' Instead of the Expected Sequence?. For more information, please follow other related articles on the PHP Chinese website!