Per Iteration Loop Variables Since Go 1.22

Since Go 1.22 each loop iteration creates fresh variables, so closures and goroutines capture that iteration value instead of silently sharing one variable.

GoData Integrity

Code

gosnippet
27 lines
package main

import "fmt"

func main() {
	envs := []string{"dev", "staging", "prod"}

	// Go 1.22 起每次迭代创建新的循环变量:每个闭包捕获当次的 env
	checks := make([]func() string, 0, len(envs))
	for _, env := range envs {
		checks = append(checks, func() string {
			return "health check: " + env
		})
	}
	for _, check := range checks {
		fmt.Println(check())
	}

	// 复现 1.22 之前的行为:跨迭代共享的变量让所有闭包看到最后一个值
	var shared string
	legacy := make([]func() string, 0, len(envs))
	for _, env := range envs {
		shared = env
		legacy = append(legacy, func() string { return shared })
	}
	fmt.Println("shared variable:", legacy[0](), legacy[1](), legacy[2]())
}

What the code does

Count the function main as the entire surface area of Per Iteration Loop Variables Since Go 1.22.

Repetition is confined to for _, env := range envs — the rest of the file is straight-line.

Using it

The demo output is labeled (shared variable:), so each printed line points back to the operation that produced it.

Key statements

legacy = append(legacy, func() string { return shared })
checks = append(checks, func() string {
return "health check: " + env
})
for _, check := range checks {
fmt.Println(check())
}

Interactive Tools for This Topic

FAQ

What does Per Iteration Loop Variables Since Go 1.22 print when run?
Invoke the file as-is — the `shared variable:` prefixes identify which step printed each line.