diff --git a/doc/go_spec.html b/doc/go_spec.html index 3c065f57cbb..529fdeff24f 100644 --- a/doc/go_spec.html +++ b/doc/go_spec.html @@ -6541,7 +6541,6 @@ additionally it may specify an init and a post statement, such as an assignment, an increment or decrement statement. The init statement may be a short variable declaration, but the post statement must not. -Variables declared by the init statement are re-used in each iteration.

@@ -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
+
+

For statements with 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.

@@ -8550,7 +8592,11 @@ passed as arguments to other (possibly generic) functions.

Go 1.22