# 恐慌：运行时错误：索引超出范围 [5] 长度为3（在协程中）

- **ID:** `go/goroutine-panic-in-goroutine`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

协程使用越界索引访问slice或数组，导致恐慌，如果不恢复则崩溃整个程序。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.0 | active | — | — |
| 1.22 | active | — | — |

## 解决方案

1. **Use recover() inside the goroutine to handle panic** (90% 成功率)
   ```
   go func() {
    defer func() {
        if r := recover(); r != nil {
            log.Println("recovered from panic:", r)
        }
    }()
    arr := []int{1,2,3}
    fmt.Println(arr[5])
}()
   ```
2. **Always check bounds before accessing slice** (95% 成功率)
   ```
   if idx < len(arr) {
    fmt.Println(arr[idx])
} else {
    log.Println("index out of bounds")
}
   ```

## 无效尝试

- **Ignoring panic and hoping it doesn't happen** — Panic crashes the program; cannot be ignored. (100% 失败率)
- **Using recover() in main goroutine only** — Recover must be called in the same goroutine that panicked; main goroutine cannot recover from child goroutine panic. (95% 失败率)
