The Goroutine Closure Variable Capture Gotcha

Fix Go goroutine closure variable capture by declaring a new variable inside the loop to snapshot the current iteration value.

The goroutine closure variable capture issue occurs because Go closures capture loop variables by reference, not by value, causing all closures to share the same variable instance. To fix this, declare a new variable inside the loop scope to capture the current value for each iteration.

for i := 0; i < n; i++ {
    j := i // Capture current value
    go func() {
        fmt.Println(j)
    }()
}