Loop variables per iteration
- Version
- 1.27
- Since
- 1.22
- Review
- Draft
Summary#
With a module go directive of 1.22 or later, a range loop that declares its iteration variables with := gives each iteration its own variables. Variables declared in the initializer of a three-part for loop also have a separate instance per iteration. A closure can capture the current value without a shadow declaration.
Syntax#
for _, name := range names {
callbacks = append(callbacks, func() { fmt.Println(name) })
}
Example#
package main
import "fmt"
func main() {
var callbacks []func()
for _, name := range []string{"red", "green", "blue"} {
callbacks = append(callbacks, func() { fmt.Println(name) })
}
for _, callback := range callbacks {
callback()
}
}
Expected output#
red
green
blue
Common mistakes#
An explicit assignment loop such as for _, name = range names still reuses the variable declared outside the loop. Check the module's go directive when investigating capture behavior.
Version applicability#
With go 1.22 or later, declared range variables are created per iteration. In a Go 1.21 module, the example closures capture the same variable and print blue three times. Add name := name inside older loops to give the closure its own copy.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0