Sobes.tech
Middle+

What will the code with goroutines and a closure of the variable city in a loop output? How to fix it?

sobes.tech AI

Answer from AI

When using goroutines in a loop with a variable closure, for example:

cities := []string{"Moscow", "London", "Paris"}
for _, city := range cities {
    go func() {
        fmt.Println(city)
    }()
}

all goroutines may output the same value — the last value of the city variable from the loop. This happens because the closure captures the variable city by reference, not its current value at each iteration.

To fix this, you need to pass the variable as a parameter to the anonymous function, thereby fixing its value for each goroutine:

for _, city := range cities {
    city := city // local copy
    go func(c string) {
        fmt.Println(c)
    }(city)
}

Or directly pass the parameter:

for _, city := range cities {
    go func(c string) {
        fmt.Println(c)
    }(city)
}

This way, each goroutine will work with its own copy of the city value.