The analyzer has detected that a goroutine captures a variable from a for or for range loop in Go versions prior to 1.22.
In Go versions prior to 1.22, a variable declared in a loop header is a single variable shared between loop iterations. Its value changes with each iteration, but no new variable is created. A closure started by a go statement captures the variable by reference and reads it as long as the loop continues to modify it.
As a result, a data race occurs, and the goroutines most often receive the value from the last iteration.
The example N1:
func Handler(w http.ResponseWriter, r *http.Request) {
items := []string{"a", "b", "c"}
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1)
go func() {
defer wg.Done()
process(item)
}()
}
wg.Wait()
}
All three goroutines use the same item variable. By the time they start running, the loop will most likely have already completed, and the process function will be called with the value "c" several times. In this case, the elements "a" and "b" may not be processed. Besides, there is no synchronization between the loop writing to item and the goroutines reading it.
To give each goroutine its own value, pass it as a function argument:
func Handler(w http.ResponseWriter, r *http.Request) {
items := []string{"a", "b", "c"}
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1)
go func(item string) {
defer wg.Done()
process(item)
}(item)
}
wg.Wait()
}
The call arguments are evaluated before the goroutine starts, so each goroutine will receive a copy of the current iteration's value. Creating a copy of the variable inside the loop body before the goroutine starts has the same effect: item := item.
The example N2:
results := make([]Result, len(jobs))
for i := 0; i < len(jobs); ++i {
go func() {
results[i] = run(jobs[i])
}()
}
A goroutine may begin executing only after the loop has finished, when i == len(jobs). In that case, accessing jobs[i] will cause a panic due to an out-of-bounds slice access. If the loop has not finished yet, several goroutines will write the result to the same results element.
The fixed code:
results := make([]Result, len(jobs))
for i := 0; i < len(jobs); i++ {
go func(i int) {
results[i] = run(jobs[i])
}(i)
}
If the project can be upgraded to Go 1.22 or later, it is enough to raise the version in the go directive in the go.mod file. Starting with Go 1.22, each iteration gets its own copy of the loop variable, and this code becomes correct.
This diagnostic rule is classified as: