5 ms·
Yep, bitten by this one on repeat myself. definitely a WTF moment each time.
by tezza 4y ago
Yep, bitten by this one on repeat myself. definitely a WTF moment each time.
- kubb 4y agosame here, happened several times when launching a goroutine inside the loop the fix was usually adding x := x before go func() { do something with x }
- masklinn 4y agoA common alternative fix is to use IIFE, since the expression must be a call. `go` evaluates everything but the final function call in the context of the caller. So go func (x int) { … } (x) Will do the same, and is easier to extract to a named function.
- Joker_vD 4y agoThe latter is also easier to re-inline accidentally because go func (x int) { do_work(x) } (x) seems like a very roundabout way to say go do_work(x) The "x := x" solution too suffers from this problem but slightly less: both idioms look like they are no-ops (while they are actually not) but at least "x := x" is weird enough to look like it was a deliberate choice, not some vestige from refactoring.
- masklinn 4y agoEr… it makes no difference? Your first version is in fact a worse way to write the second one.
- Joker_vD 4y agoHuh. Now the closure-capturing in Go makes even less to me: instead of capturing the variable's current value it captures the variable itself i.e. puts &x into the closure instead of x — and no other piece of Go does that, although I was sure "go fun(args)" passed args by-ref but apparently not. What's even the point of capturing the variable itself? To allow for writing inline callbacks that could sneakily mutate loop-local variables?
- masklinn 4y agoMore generally allow the closure to write to its environment. That is the normal behaviour of closures in imperative langages, Java being the major exception because it rejects closing over non-final variable (and obviously that only blocks assignment, if the object is mutable you can do what you want to it).
- gpderetta 4y agoIn c++ close by value/reference is under programmer control and there is no default
- deleted 4y ago[deleted]
- randomswede 4y agoWhat would be the use of closing over the value rather than the variable? That would stop a lot of interesting use of closed-over variables (like persisting values from call to call).
- masklinn 4y agoIn fairness while that would be a lot less convenient in reference-based langages in Go you could just close over a pointer to the variable, making the relationship explicit. That’s how you’d do it using a [=] lambda in c++ or a move closure in rust.