Join GitHub today
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.Sign up
spec: scope and re-use of loop variables is not fully specified #7834
For "for" statements, the spec only partially covers the scope and reuse of variables declared with a short variable declaration, as well as for the use of existing variables. When using the `range` keyword, the spec says that „The iteration variables may be declared by the "range" clause using a form of short variable declaration (:=). [...] and their scope ends at the end of the "for" statement; they are re-used in each iteration. If the iteration variables are declared outside the "for" statement, after execution their values will be those of the last iteration“ All of these statements are also true for "for" statements that use a ForClause, that is `for i := 0; i < N; i++`, but the spec does not explicitly mention this. The section on "Short variable declarations" does say that „In some contexts such as the initializers for "if", "for", or "switch" statements, they can be used to declare local temporary variables“ but "local temporary variables" is vague and only covers the fact that their scope ends at the end of the "for" statement; it does not say anything about the variables' re-use. And obviously it doesn't cover the use of variables that are declared outside the "for" statement. I propose to split the first quoted paragraph into two: One that's general to the "for" statement itself, and one that only covers the bits that are specific to the use of "range".
I opted for repeating some of the wording for clarity. Note that the variables declared in a regular for loop's init statement (w/o a range clause) are not necessarily "iteration variables". https://golang.org/cl/148940044
Status changed to Started.
This issue was closed.