go
runtime_error
ai_generated
true
panic: 运行时错误:无效的内存地址或空指针解引用
panic: runtime error: invalid memory address or nil pointer dereference
ID: go/protobuf-unknown-field-nil-pointer
80%修复率
88%置信度
0证据数
2024-06-21首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| google.golang.org/protobuf v1.26+ | active | — | — | — |
根因分析
访问从未设置的 proto 消息的子消息字段会返回 nil。调用 getter 是安全的,但对 nil 子消息直接进行字段访问会 panic。
English
Accessing a submessage field of a proto message that was never set returns nil. Calling a getter is safe, but direct field access on a nil submessage panics.
解决方案
-
95% 成功率
// BAD: msg.Address.City // GOOD: city := msg.GetAddress().GetCity() if city == "" { city = "unknown" } -
93% 成功率
if addr := msg.GetAddress(); addr != nil { fmt.Println(addr.Street) } else { fmt.Println("address not set") }
无效尝试
常见但无效的做法:
-
80% 失败
recover hides the bug and leaves the RPC handler in an inconsistent state; the underlying nil field is still unset.
-
65% 失败
The peer or the server-side merge may still leave optional submessages unset, so the panic returns whenever the message is absent.