Unbreaking the Loop: Go 1.22 fixes for loops
On go's #1 gotcha, its workaround and what the next go version brings
As this year comes to an end, a new golang release approaches which promises to fix the existing issue of the reference loop values.
But first, let’s start with understanding what the ‘issue’ is by showing the difference between passing by value and by reference. The following code will print what you probably expect: the values 0 to 4 in some random order.

Now, we’ve all probably made the error at some point of referencing a variable loop outside its loop scope. If we update the above code to pass by reference, the result will now be 5 5 5 5 5, probably not what we were expecting.

The issue we're encountering is related to the closure capturing the loop variable i
by reference. By the time the goroutines are executed in the main
function, they all refer to the final value of i
(which is 5) because the loop has completed.
To fix this, you need to create a new variable inside the loop for each iteration, allowing each goroutine to capture a distinct variable. You can achieve this by introducing a new variable in the loop scope:

In the above, each goroutine captures a different variable val
, and the sync.WaitGroup
ensures that the main
function waits for all goroutines to finish before exiting. The output should now be the values 0 to 4 as expected.
This problem was so common that Go 1.21 contains a new experimental feature which changes the semantics so that each iteration would use a new variable. You can turn it on by exporting the flag export GOEXPERIMENT=loopvar. This behaviour will be enabled by default in Go 1.22. Let’s say we have the following example:
If we enable the flag, this time it will produce the following output:
With modifications like these, it's evident that Go is becoming increasingly welcoming to beginners. Tackling issues such as loop variable capture will significantly accelerate the onboarding process for new developers, enhancing the overall experience for gophers at any skill level.
Resources: