go
runtime_error
ai_generated
true
恐慌:运行时错误:索引超出范围 [5],长度为 5(闭包捕获)
panic: runtime error: index out of range [5] with length 5 (closure capture)
ID: go/goroutine-slice-iteration-closure
80%修复率
88%置信度
0证据数
2024-11-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
goroutine 闭包通过引用捕获循环变量,导致 goroutine 在循环后执行时索引值意外。
English
A goroutine closure captures a loop variable by reference, leading to unexpected index values when the goroutine executes after the loop.
解决方案
-
95% 成功率 Copy loop variable to a local variable inside the loop
for i := 0; i < 5; i++ { i := i go func() { fmt.Println(i) }() } -
95% 成功率 Pass the value as an argument to the goroutine
for i := 0; i < 5; i++ { go func(val int) { fmt.Println(val) }(i) }
无效尝试
常见但无效的做法:
-
Using a sleep inside the loop to 'wait' for goroutines
80% 失败
Does not fix closure capture; goroutines still see final index.
-
Using a different variable name inside the loop without copying
70% 失败
All goroutines still reference the same variable.