The Loop Variable Capture Gotcha in Go (Pre-1.22)

Fix the Go loop variable capture bug in pre-1.22 versions by assigning the loop variable to a new local variable inside the loop body.

In Go versions prior to 1.22, loop variables in for loops are reused across iterations, causing closures to capture the same variable instance rather than a copy of its value at that iteration. To fix this, explicitly assign the loop variable to a new local variable inside the loop body before using it in a closure.

for i := 0; i < len(items); i++ {
    index := i // Create a new variable for this iteration
    go func() {
        fmt.Println(items[index]) // Captures the correct value
    }()
}