4 ms·
The design for #1 is good and consistent. There are not reference values in Go. All assignments in Go are value copies. BTW, in fact, the ", _" in the author's
by tapirl 9y ago
The design for #1 is good and consistent. There are not reference values in Go. All assignments in Go are value copies.
BTW, in fact, the ", _" in the author's code can be omitted.
for idx := range zoo {
zoo[idx].legs = 999
}
- dilap 9y agoHypothetically, 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 (capture of x by a closure inside the for loop not doing what we want, and #1 in the original article). I think the downside would be the concept of references doesn't exist anywhere else in Go (so the "for ... range" loop would have to be its own thing, rather than explainable as a transformation to simpler code) & maybe also implementation concerns I don't know about. But if we were willing to pay the complexity cost it would make the language nicer, IMO. (I'm not saying we should be willing to pay the complexity cost though -- a lot of Go's charm is how much the language leaves out.)
- 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.