Why Go 1.22’s New Loop Variable Scoping Fix Solves Common Closure Bugs
Go 1.22 changes the for‑loop variable scope so that each iteration receives its own copy, eliminating the long‑standing closure pitfall that caused incorrect outputs in concurrent programs and simplifying range usage for developers.
Go 1.22 Changes to for‑loop Variable Scope
In Go 1.22 the language specification was updated so that the loop variable in a for statement is re‑declared for each iteration. Earlier versions kept a single variable for the whole loop, which caused subtle bugs when the variable was captured by closures, especially in concurrent code.
What the change fixes
The previous behaviour meant that all closures created inside a loop would reference the same variable, leading to repeated or unexpected values when the closures were later executed. This issue affected many Go programs, from beginner code to production services such as Let’s Encrypt, which lost three million certificates in 2020 due to an incorrect loop handling.
Example before Go 1.22
for i := 0; i < 5; i++ {
prints = append(prints, func() { println(i) })
i++
}
for _, p := range prints {
p()
}Running the above on Go 1.21 or earlier prints:
6
6
6
1
2
3
6
6
6Behavior in Go 1.22
With the new scoping rule each closure captures the value of i at the moment of the iteration, producing the expected sequence:
1
3
5
1
2
3
1
3
5Simplified range syntax
Go 1.22 also introduces a more concise range form that can replace the traditional C‑style loop:
(i = 0; i < 5; i++)Now you can write:
for i := range(5)This iterates five times, yielding values 0‑4, and reduces boilerplate in benchmarks and repetitive code.
Enabling the experimental iterator feature
The new iterator capability can be turned on with the GOEXPERIMENT=rangefunc environment variable, allowing any function to be used as an iterator, similar to generators in other languages.
GOEXPERIMENT=rangefuncDevelopers have praised the change for making concurrent testing and closure‑based patterns easier to write without extra linter work.
Related reading
Programming 20 years: advice from a 38‑year‑old Google engineer
Which programming language is fastest and most energy‑efficient?
My MacBook development setup (2024 edition)
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
