5 ms·
I think there's a bug, tho it might not make a difference to the results: for i := 0; i < 10; i++ { go func() { f(i) // sees whatever valu
by networkimprov 6y ago
I think there's a bug, tho it might not make a difference to the results:
for i := 0; i < 10; i++ {
go func() {
f(i) // sees whatever value i has when f() is called, usually 10
}()
}
- thewakalix 6y agoFor 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.
- mykowebhn 6y agoThis is a very common newbie mistake. Fix by passing in i. for i := 0; i < 10; i++ { go func(i int) { f(i) // sees whatever value i has when f() is called, usually 10 }(i) }
- thereare5lights 6y agoThis looks very much like the mistake in javascript with callbacks in for loops.
- panopticon 6y agoNote that using `let` instead of `var` in your for-loop fixes this in JavaScript (ignoring IE's faulty implemention of `let`).
- deleted 6y ago[deleted]
- rmrfrmrf 6y agoabsolutely wild to me that Real Engineers (TM) complained about this in JavaScript for years only for it to be called a "newbie mistake" in Go.
- shawnz 6y agoThe same is true of most of JavaScript's warts
- matklad 6y agoThanks for the correction, that is indeed a bug!
- jayd16 6y agoInteresting. Integers are captured by reference in Go?
- shawnz 6y agoClosures capture all in-scope variables by reference in most languages. Same situation in Python for example: https://stackoverflow.com/questions/54288926/python-loops-and-closures https://stackoverflow.com/questions/54288926/python-loops-an...
- closeparen 6y agoYou can get bitten by a similar problem without closures if you stick a loop variable in an array. The loop variable is one address with contents mutating each iteration.
- masklinn 6y ago> You can get bitten by a similar problem without closures if you stick a loop variable in an array. Surely only if you store it indirectly, otherwise it'll be copied into the array.