Sobes.tech
Senior

1.21 func main() { var nums []*int for i := 0; i < 10; i++ { nums = append(nums, &i) } for _, v := range nums { go func() { fmt.Println(v) }() } }

sobes.tech AI

Vastus AI-lt

In this code, there is a classic closure bug in the loop when working with goroutines and pointers.

The variable i in the loop changes, and pointers to the same variable i are added to the nums slice. As a result, all elements of nums point to the same memory location, which after the loop ends contains the value 9.

When goroutines are launched, they all print the same value — the address pointed to by v will be the same for all elements.

To fix this, you need to create a new variable inside the loop so that each pointer points to a separate value:

func main() {
    var nums []*int
    for i := 0; i < 10; i++ {
        val := i
        nums = append(nums, &val)
    }

    for _, v := range nums {
        go func(v *int) {
            fmt.Println(*v)
        }(v)
    }
}

Here, we create val inside the loop and pass v as a parameter to an anonymous function, which guarantees correct capturing of the value.