go
runtime_error
ai_generated
true
恐慌:运行时错误:索引超出范围 [0],长度为0(在协程中)
panic: runtime error: index out of range [0] with length 0 (in goroutine)
ID: go/goroutine-slice-concurrent-access
80%修复率
85%置信度
0证据数
2025-01-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
多个协程在没有同步的情况下向切片追加元素,导致切片损坏或访问不正确。
English
Multiple goroutines append to a slice without synchronization, causing the slice to be corrupted or accessed incorrectly.
解决方案
-
98% 成功率 Use sync.Mutex to protect slice append
var mu sync.Mutex var s []int for i := 0; i < 10; i++ { go func(val int) { mu.Lock() s = append(s, val) mu.Unlock() }(i) } -
95% 成功率 Use a channel to collect results
ch := make(chan int, 10) for i := 0; i < 10; i++ { go func(val int) { ch <- val }(i) } var s []int for i := 0; i < 10; i++ { s = append(s, <-ch) }
无效尝试
常见但无效的做法:
-
Pre-allocating slice capacity
80% 失败
Pre-allocation does not prevent concurrent append races; the length field is still modified concurrently.
-
Using a local slice per goroutine and merging later
70% 失败
Merging slices concurrently can still cause races if not synchronized.