go
type_error
ai_generated
true
error: expected result 3, got 3 (all goroutines see same loop variable)
ID: go/loop-variable-capture
80%Fix Rate
90%Confidence
0Evidence
2024-02-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.19 | active | — | — | — |
| 1.20 | active | — | — | — |
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
Root Cause
Before Go 1.22, goroutines launched inside a for loop captured the same loop variable, so all goroutines observed the final value. This causes subtle output bugs and races.
generic中文
在 Go 1.22 之前,for 循环内启动的 goroutine 捕获同一个循环变量,导致所有 goroutine 看到最终值。这会造成微妙的输出错误和竞态。
Workarounds
-
95% success
Shadow the loop variable: for _, v := range items { v := v; go func(){ use(v) }() } -
92% success
Upgrade to Go 1.22+ where loop variables are per-iteration by default, or pass v as an argument: go func(v T){...}(v)
Dead Ends
Common approaches that don't work:
-
90% fail
The variable is shared; sleeping changes nothing about which value is read.
-
95% fail
Scheduling does not affect variable capture semantics.