panic:运行时错误:无效的内存地址或空指针解引用
panic: runtime error: invalid memory address or nil pointer dereference
ID: go/proto-nil-pointer-deref-proto-message
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| google.golang.org/protobuf 1.x | active | — | — | — |
根因分析
解引用了一个 nil 的 *pb.Message,通常来自 nil 的嵌套消息字段,或与错误一起返回的 nil 响应。在 protobuf Go 中,读取 nil 消息字段返回 nil,对 nil 调用 getter 是安全的,但直接字段访问则不是。
English
A nil *pb.Message was dereferenced, typically from a nil nested message field or a nil response returned alongside an error. In protobuf Go, reading a nil message field returns nil, and calling a getter on nil is safe but direct field access is not.
解决方案
-
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 -
85% 成功率
Initialize nested messages explicitly before writing to them: if resp.User == nil { resp.User = &pb.User{} } resp.User.Name = "alice"
无效尝试
常见但无效的做法:
-
80% 失败
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.
-
70% 失败
The nil is often in a nested field (e.g. resp.User.Address); checking only the outer message still panics on the inner access.