go
data_error
ai_generated
true
error:所有 goroutine 看到的是循环变量最终值(i = N)而非各自迭代值
error: all goroutines see final loop variable value (i = N) instead of their iteration value
ID: go/loop-variable-capture-goroutine
80%修复率
90%置信度
0证据数
2024-01-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.16 | active | — | — | — |
| 1.20 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
在 Go 1.22 之前,循环变量在各迭代间共享。作为 goroutine 启动的闭包捕获同一个变量,运行时其值已推进到最终值。
English
Before Go 1.22, the loop variable is shared across iterations. Closures launched as goroutines capture the same variable, which by the time they run has advanced to the final value.
解决方案
-
98% 成功率
for i := 0; i < n; i++ { i := i go func() { use(i) }() } -
97% 成功率
// go.mod: go 1.22 for i := 0; i < n; i++ { go func() { use(i) }() }
无效尝试
常见但无效的做法:
-
85% 失败
Sleeps are not deterministic; the variable is still shared and may advance before the goroutine reads it.
-
80% 失败
Serializing execution does not change variable capture semantics; the final value bug persists.