go
runtime_error
ai_generated
true
恐慌:运行时错误:索引超出范围 [5],长度为 5(在 goroutine 中)
panic: runtime error: index out of range [5] with length 5 (in goroutine)
ID: go/goroutine-panic-uncaught
80%修复率
86%置信度
0证据数
2024-08-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.23 | active | — | — | — |
根因分析
goroutine 访问数组或切片的越界索引,导致恐慌未被恢复,整个程序崩溃。
English
A goroutine accesses an array or slice index that is out of bounds, causing a panic that is not recovered, crashing the entire program.
解决方案
-
90% 成功率 Add a deferred recover inside the goroutine to handle panics gracefully
go func() { defer func() { if r := recover(); r != nil { log.Printf("Recovered in goroutine: %v", r) } }() arr := make([]int, 5) arr[5] = 10 // panic here }() -
95% 成功率 Check slice bounds before accessing
arr := make([]int, 5) index := 5 if index < len(arr) { arr[index] = 10 } else { log.Println("Index out of bounds") }
无效尝试
常见但无效的做法:
-
Adding recover in main but not in the goroutine
80% 失败
Panic in goroutine is not caught by main's recover unless deferred in the goroutine itself.
-
Using a larger array but not fixing the index logic
70% 失败
Band-aid solution; index may still go out of bounds in other cases.