go
runtime_error
ai_generated
true
panic: runtime error: index out of range [0] with length 0 (in goroutine)
ID: go/goroutine-slice-concurrent-access
80%Fix Rate
85%Confidence
0Evidence
2025-01-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
Root Cause
Multiple goroutines append to a slice without synchronization, causing the slice to be corrupted or accessed incorrectly.
generic中文
多个协程在没有同步的情况下向切片追加元素,导致切片损坏或访问不正确。
Workarounds
-
98% success 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% success 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) }
Dead Ends
Common approaches that don't work:
-
Pre-allocating slice capacity
80% fail
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% fail
Merging slices concurrently can still cause races if not synchronized.