go
runtime_error
ai_generated
true
恐慌:运行时错误:索引超出范围 [5] 长度为3(在协程中)
panic: runtime error: index out of range [5] with length 3 (in goroutine)
ID: go/goroutine-panic-in-goroutine
80%修复率
87%置信度
0证据数
2025-03-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
协程使用越界索引访问slice或数组,导致恐慌,如果不恢复则崩溃整个程序。
English
Goroutine accesses slice or array with out-of-bounds index, causing panic that crashes the entire program if not recovered.
解决方案
-
90% 成功率 Use recover() inside the goroutine to handle panic
go func() { defer func() { if r := recover(); r != nil { log.Println("recovered from panic:", r) } }() arr := []int{1,2,3} fmt.Println(arr[5]) }() -
95% 成功率 Always check bounds before accessing slice
if idx < len(arr) { fmt.Println(arr[idx]) } else { log.Println("index out of bounds") }
无效尝试
常见但无效的做法:
-
Ignoring panic and hoping it doesn't happen
100% 失败
Panic crashes the program; cannot be ignored.
-
Using recover() in main goroutine only
95% 失败
Recover must be called in the same goroutine that panicked; main goroutine cannot recover from child goroutine panic.