3 ms·
> Go 1.22 made variables introduced by for loops scoped per iteration, rather than per loop, addressing a long-standing language “gotcha”. This does fixes the
by tapirl 2y ago
> Go 1.22 made variables introduced by for loops scoped per iteration, rather than per loop, addressing a long-standing language “gotcha”.
This does fixes the "for-range" loop gotcha, but brings several gotchas to the 3-clause "for;;" loops:
* https://go101.org/blog/2024-03-01-for-loop-semantic-changes-in-go-1.22.html https://go101.org/blog/2024-03-01-for-loop-semantic-changes-...
* https://github.com/golang/go/issues/66156 https://github.com/golang/go/issues/66156
* https://x.com/zigo_101/status/1856173025839960333 https://x.com/zigo_101/status/1856173025839960333
* https://x.com/zigo_101/status/1854918262523621805 https://x.com/zigo_101/status/1854918262523621805
* https://x.com/zigo_101/status/1854213142177624169 https://x.com/zigo_101/status/1854213142177624169
- nine_k 2y agoTo me, it's not a gotcha. As the github issue discussion notices, loops where the semantics depend on the identity of the loop variable to remain the same over the 3-clause loop iteration is exceedingly rare. I'd also say it's contrived and should not pass a code review. Funnily, a 3-clause loop in Go (and in C) is actually a reduce(), where the loop variable's value, possibly touched by the iteration, is then directed back to the next iteration. This makes it more powerful (e.g. can traverse graphs, etc), but also more complex than it looks in the case of an integer and increment.