BTW, in fact, the ", _" in the author's code can be omitted.
for idx := range zoo {
zoo[idx].legs = 999
}BTW, in fact, the ", _" in the author's code can be omitted.
for idx := range zoo {
zoo[idx].legs = 999
} 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.)
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…)
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.
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)
Yeah, it's pretty clumsy though.