From 26ba75fe5927a078695288da0efefba37b4a4d6e Mon Sep 17 00:00:00 2001
From: Robert Griesemer
@@ -6573,6 +6572,48 @@ for cond { S() } is the same as for ; cond ; { S() } for { S() } is the same as for true { S() }+
+Each iteration has its own separate declared variable (or variables) +[Go 1.22]. +The variable used by the first iteration is declared by the init statement. +The variable used by each subsequent iteration is declared implicitly before +executing the post statement and initialized to the value of the previous +iteration's variable at that moment. +
+ ++var prints []func() +for i := 0; i < 5; i++ { + prints = append(prints, func() { println(i) }) + i++ +} +for _, p := range prints { + p() +} ++ +
+prints +
+ ++0 +3 +5 ++ +
+Prior to [Go 1.22], iterations share one set of variables +instead of having their own separate variables. +In that case, the example above prints +
+ ++6 +6 +6 ++
range
clause
@@ -6677,9 +6718,10 @@ The iteration variables may be declared by the "range" clause using a form of
short variable declaration
(:=
).
In this case their types are set to the types of the respective iteration values
-and their scope is the block of the "for"
-statement; they are re-used in each iteration.
-If the iteration variables are declared outside the "for" statement,
+and their scope is the block of the "for" statement;
+each iteration has its own separate variables [Go 1.22]
+(see also "for" statements with a ForClause).
+If the iteration variables are declared outside the “for” statement,
after execution their values will be those of the last iteration.