Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Concepts

Go loop variable semantics

Reference for Go's per-iteration loop variables: how for loops changed in Go 1.22, closures and goroutines in loops, the old shared variable, and version rules.

Before Go 1.22, a for loop declared its variable once for the whole loop. Every iteration updated that same variable, so a closure, goroutine or pointer created inside the loop body saw whatever value the variable held when it finally ran, usually the last one. It was one of the most common Go bugs.

Since Go 1.22 each iteration gets its own copy of the variable, for three-clause loops and for range loops alike. A closure that captures i now captures that iteration's i, and &i is a different address each time. The change applies to modules whose go.mod says go 1.22 or later; older modules keep the old behavior until you raise the version.

Go
var funcs []func() int
for i := 0; i < 3; i++ {
	funcs = append(funcs, func() int { return i })
}
// Go 1.22+: calling them returns 0, 1, 2. Before 1.22: 3, 3, 3.

Try it

Go Closures and pointers capture one value per iteration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go How the old shared variable behaved

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Loop form Variable lifetime (Go 1.22+)
for i := 0; i < n; i++ { ... } A new i per iteration
for i, v := range x { ... } New i and v per iteration
for i := range 10 { ... } A new i per iteration (range over integers, Go 1.22)
for v := range seq { ... } New variable per iteration (range-over-func iterators, Go 1.23)
for i = 0; i < n; i++ { ... } Shared i: it was declared outside the loop, so nothing changes

How the three-clause loop works. Before each iteration after the first, the compiler creates a fresh variable, copies the previous iteration's final value into it, and then runs the post statement (i++) on the fresh variable. The condition and the body see the new copy. So a closure created in iteration 1 keeps the value that iteration ended with, and the loop still counts normally.

Version control. The language version comes from the go line of go.mod (or go.work). A file can override it with a //go:build go1.21 line (for an older meaning) or //go:build go1.22 (for the new one), as long as the module's toolchain supports that version. The GOEXPERIMENT=loopvar switch from Go 1.21 is only of historical interest.

Errors and edge cases: the compiler reports nothing when old code is built under the new rules; behavior changes silently. The rare programs that relied on the shared variable (for example, comparing &i across iterations) break. Performance impact is generally negligible, because the compiler only allocates separate copies when the variable escapes.

Usage notes

  • Remove the i := i workaround if your module is at Go 1.22 or later. It is harmless, but redundant.
  • Raising the go line in go.mod changes semantics. When you upgrade an old module, check loops that start goroutines, defer in loops or store &v. go vet's loopclosure check flagged the common mistakes under the old rules.
  • defer in a loop now closes over the iteration's variable too, but it still runs at function end, not at the end of the iteration. For per-iteration cleanup, call a function.
  • Taking the address of the range value is now safe: for _, v := range items { out = append(out, &v) } gives pointers to distinct copies. It copies each element, though, so &items[i] is better when you need pointers into the slice.
  • Shared on purpose. If you want to read the variable's final value from a closure, declare it outside the loop.
  • Mixed code bases. Libraries compiled with older go lines keep old behavior even inside a newer program. The version is per module, not per binary.
  • Tests that depend on timing around goroutines in loops can change behavior when a module is upgraded, since the output was probably wrong before.