# 恐慌：运行时错误：无效的内存地址或空指针解引用（在 goroutine 中）

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

## 根因

在 goroutine 内部发生空指针解引用，导致未恢复的恐慌。当 goroutine 未经检查就访问空指针时，可能会发生这种情况。

## 版本兼容性

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

## 解决方案

1. **Add a deferred recover inside the goroutine** (90% 成功率)
   ```
   go func() {
    defer func() {
        if r := recover(); r != nil {
            log.Printf("Recovered in goroutine: %v", r)
        }
    }()
    // code that may panic
    var p *int
    *p = 42 // nil pointer dereference
}()
   ```
2. **Check for nil pointers before dereferencing** (95% 成功率)
   ```
   if p != nil {
    *p = 42
} else {
    log.Println("nil pointer")
}
   ```

## 无效尝试

- **Adding a recover in the main goroutine only** — recover() only works within the same goroutine; panics in other goroutines cannot be recovered from the main goroutine. (95% 失败率)
- **Ignoring the panic and hoping the program continues** — An unhandled panic in any goroutine crashes the entire program. (99% 失败率)
