go
runtime_error
ai_generated
true
panic: runtime error: invalid memory address or nil pointer dereference
ID: go/proto-nil-pointer-deref-proto-message
80%Fix Rate
88%Confidence
0Evidence
2024-04-18First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| google.golang.org/protobuf 1.x | active | — | — | — |
Root Cause
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.
generic中文
解引用了一个 nil 的 *pb.Message,通常来自 nil 的嵌套消息字段,或与错误一起返回的 nil 响应。在 protobuf Go 中,读取 nil 消息字段返回 nil,对 nil 调用 getter 是安全的,但直接字段访问则不是。
Workarounds
-
92% success
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% success
Initialize nested messages explicitly before writing to them: if resp.User == nil { resp.User = &pb.User{} } resp.User.Name = "alice"
Dead Ends
Common approaches that don't work:
-
80% fail
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% fail
The nil is often in a nested field (e.g. resp.User.Address); checking only the outer message still panics on the inner access.