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)
}()
}
The Goroutine Closure Variable Capture Gotcha occurs because Go reuses the same memory location for loop variables, so every function created inside the loop ends up reading the final value of that variable instead of the value at the time it was created. Think of it like writing a note on a whiteboard that gets erased and rewritten every minute; if you take a photo of the board later, you only see the last thing written, not the history. Creating a new variable inside the loop acts like taking a snapshot of the value at that exact moment.