(no title)
travisd | 2 years ago
add_n = []
for n in range(10):
add_n.append(lambda x: x + n)
add_n[9](10) # 19
add_n[0](10) # 19
This isn't to say it's *not* a footgun (and it has bit me in Python before), but it's much worse in Go due to the idiomatic use of goroutines in a loop: for i := 0; i < 10; i++ {
go func() { fmt.Printf("num: %d\n", i) }()
}
eru|2 years ago
(Do take what I wrote with a grain of salt. Either the above is already a problem, or perhaps you also need to mix in list-comprehension expressions, too, to surface the bug.)
nerdponx|2 years ago
Equivalents:
Late binding applies in both cases of course, but in the first case it doesn't matter, whereas in the latter case it matters.I think early binding would produce the same result in both cases.
Spivak|2 years ago
eru|2 years ago
hinkley|2 years ago
lmm|2 years ago
panzi|2 years ago
unknown|2 years ago
[deleted]
simiones|2 years ago
The bigger problem in Go is the for with range loop:
This is the one they are changing.Edit: it looks like they're actually changing both of these, which is more unexpected to me. I think the C# behavior makes more sense, where only the foreach loop has a new binding of the variable in each iteration, but the normal for loop has a single lifetime.
o11c|2 years ago
This makes it clear: the underlying problem is NOT about for loops - it's closures that are broken.
nerdponx|2 years ago
jshen|2 years ago
_ikke_|2 years ago
So it will warn in certain situations, but not all of them
simiones|2 years ago
It might complain about the race condition, to be fair, but the same issue can be reproduced without goroutines and it would be completely correct code per the semantics.
Frotag|2 years ago