3 ms·
Go loops define pointers for scope-defined variables at the loop, rather than iteration, level, so there's a common "gotcha" where you intern a pointer to acces
by HillRat 3y ago
Go loops define pointers for scope-defined variables at the loop, rather than iteration, level, so there's a common "gotcha" where you intern a pointer to access it outside of the loop (such as pushing it onto an array), and then discover that its value is clobbered by subsequent runs of the loop. There is a proposal to change this, since it's a source of confusion and bugs, particularly when `range`ing over pointers.
What the code snippet demonstrates is that, for a contrived scenario, the proposal in question also creates an unexpected result when you expect pointers to remain stable between loop iterations. To be honest, I can't think of any time where this would be an issue for me (as opposed to writing `foo := foo`); Go has quite a bit of cognitive friction in its loop semantics, so anything to reduce unexpected behavior is welcome to my mind.