Compare loop-variable capture before and after Go 1.22
Compare loop-variable capture before and after Go 1.22
For packages using Go language version 1.22 or later, iteration variables declared by a for loop (including range with :=) are distinct for each iteration. Older language versions reuse the declared iteration variables. A range loop assigning to an existing variable with = still reuses that variable. Set the module go directive to match the intended language version.
package main
import ( "fmt")
func main() { var reads []func() int for _, v := range []int{1, 2, 3} { reads = append(reads, func() int { return v }) } for _, read := range reads { fmt.Println(read()) }}With Go 1.22+ language semantics each closure reads its own v. In a module using Go 1.21 semantics the same program prints 3 three times. The installed compiler alone does not determine the language version of every package. These closures are called after the loop, without concurrency.
Expected output:
123Assignment still shares a variable
package main
import ( "fmt")
func main() { var v int var reads []func() int for _, v = range []int{1, 2, 3} { reads = append(reads, func() int { return v }) } for _, read := range reads { fmt.Println(read()) }}All closures refer to the same preexisting v. To make a separate variable even in old language versions, use snapshot := v inside the loop body and capture snapshot. This does not deep-copy referenced data such as slice elements.
Expected output:
333Try it locally
Use range with = and a predeclared v for values 4 and 8. Inside the body copy v to snapshot using :=. Append a closure that returns snapshot, and print results after the loop.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Scope and closures 04: Compare loop-variable capture before and after Go 1.22
Check the lesson objective before moving on.
What do closures over range := iteration variables return after the loop under Go 1.22+?
Which pattern still shares v in Go 1.22?