# panic：运行时错误：无效的内存地址或空指针解引用

- **ID:** `go/proto-nil-pointer-deref-proto-message`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

解引用了一个 nil 的 *pb.Message，通常来自 nil 的嵌套消息字段，或与错误一起返回的 nil 响应。在 protobuf Go 中，读取 nil 消息字段返回 nil，对 nil 调用 getter 是安全的，但直接字段访问则不是。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| google.golang.org/protobuf 1.x | active | — | — |

## 解决方案

1. **** (92% 成功率)
   ```
   Always check the error before touching the response, and use generated getters which are nil-safe:

resp, err := client.GetUser(ctx, req)
if err != nil { return err }
name := resp.GetUser().GetName() // getters return zero values on nil
   ```
2. **** (85% 成功率)
   ```
   Initialize nested messages explicitly before writing to them:

if resp.User == nil { resp.User = &pb.User{} }
resp.User.Name = "alice"
   ```

## 无效尝试

- **** — Recovering hides the bug and leaves the program in an inconsistent state; the nil is a logic error that must be fixed at the source. (80% 失败率)
- **** — The nil is often in a nested field (e.g. resp.User.Address); checking only the outer message still panics on the inner access. (70% 失败率)
