3 ms·
> Hypothetically, if the language defined for i, x := range xs to have x repeatedly be a new reference to each of xs members, it seems like we'd avoid 2 gotchya
by Merovius 9y ago
> Hypothetically, if the language defined for i, x := range xs to have x repeatedly be a new reference to each of xs members, it seems like we'd avoid 2 gotchyas
I'm not convinced. I believe what you'd end up with is that someone will write a "Common Gotchas in Go" article about how, if you think you are operating on a copy in the loop, you are actually operating on a reference.
Really, it seems very non-obvious to me, why one would be a less surprising behavior than the other.
(The fact that the loop variables are not scoped to the loop body - i.e. closures will share the references - is another issue and that I would pretty unambiguously call a gotcha that should be fixed…)
- dilap 9y agoYou think so? It just feels like I basically never want it to be a copy, but you do frequently want to modify the element you're iterating over. It actually pushes you to design things in ways you might otherwise not. E.g., instead of []X you'll have []*X just so it'll be easier to modify from inside a loop.
- Merovius 9y ago> It just feels like I basically never want it to be a copy, but you do frequently want to modify the element you're iterating over. Feels differently to me :) > It actually pushes you to design things in ways you might otherwise not. E.g., instead of []X you'll have []* X just so it'll be easier to modify from inside a loop. Never do that. Instead I use indexes when I actually want to access the element. (Where I do do that is in maps, but not because of range, but because index-expressions over maps are not addressable)
- dilap 9y ago> Never do that. Instead I use indexes when I actually want to access the element. Yeah, it's pretty clumsy though.