Proposal: Less error-prone loop variable scoping
I have to admit that, as a C&#x2F;C++ programmer, I find this entire thing a bit bizarre.<p>In C and C++, <i>of course</i> a for loop induction variable is reused for each iteration.  And if you take the address of the variable and keep it around for too long, you get to keep all the pieces and possibly the exploitable UAF vulnerability, too.  (Never mind that, prior to C99, C induction variables were always in an enclosing scope, and this would be fairly obvious from reading the code.)<p>In Rust, code like the examples wouldn’t compile.  If you want to copy a value to the heap and take a reference, you need to <i>say so</i>.  And it will be quite clear whether you are keeping a boxed copy or whether you are keeping a reference to the original object. (And the object can’t mutate out from under you unexpectedly in either case — a non-mutable reference prevents mutation!)<p>So the fact that, in Go, one might rely on automatic promotion of an induction variable (which obviously gets mutated every iteration!) to the heap, and thus get confused about precisely which value is promoted to the heap, seems weird from my perspective.  IMO one might reasonably argue that the problem is that this pattern works <i>at all</i>, not that it works in the way that people usually don’t want.<p>edit: in C++, with range-based for, the induction variable is <i>gone</i> after each iteration. So taking a reference that outlives the iteration is invalid, and if you’re lucky, the compiler will warn.  The confusing cases from the Go proposal are that invalid in C++, not confusing.