Two ways to fix the closure problem:
// Method 1: Pass as argument
for i := 0; i < 3; i++ {
go func(n int) {
fmt.Println(n)
}(i)
}
// Method 2: Local copy
for i := 0; i < 3; i++ {
i := i // Creates new variable
go func() {
fmt.Println(i)
}()
}
Both methods ensure each goroutine gets its own copy of the value.