3 ms·
For the curious reader: this can be solved by simply passing i as a parameter. for i := 0; i < 10; i++ { go func(i int) { f(i)
by thewakalix 6y ago
For the curious reader: this can be solved by simply passing i as a parameter.
for i := 0; i < 10; i++ {
go func(i int) {
f(i)
}(i)
}
- networkimprov 6y agoOr commonly, tho perhaps confusingly: for i := 0; i < 10 i++ { i := i // new variable i for every iteration go func() { f(i) }() }
- Groxx 6y agoYea. I do this personally - it's easy copypasta since it infers types for you, and as it shadows the iteration var it's impossible to use the wrong one. Same trick works for other local vars e.g. outside the loop, though at that point it's just as not-copypasta-able as the `func(arg){}(arg)` construct.