go runtime_error ai_generated true

panic: runtime error: invalid memory address or nil pointer dereference

ID: go/protobuf-unknown-field-nil-pointer

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-06-21First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
google.golang.org/protobuf v1.26+ active — — —

Root Cause

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.

generic

中文

访问从未设置的 proto 消息的子消息字段会返回 nil。调用 getter 是安全的,但对 nil 子消息直接进行字段访问会 panic。

Workarounds

  1. 95% success
    // BAD: msg.Address.City
    // GOOD:
    city := msg.GetAddress().GetCity()
    if city == "" { city = "unknown" }
  2. 93% success
    if addr := msg.GetAddress(); addr != nil {
        fmt.Println(addr.Street)
    } else {
        fmt.Println("address not set")
    }

Dead Ends

Common approaches that don't work:

  1. 80% fail

    recover hides the bug and leaves the RPC handler in an inconsistent state; the underlying nil field is still unset.

  2. 65% fail

    The peer or the server-side merge may still leave optional submessages unset, so the panic returns whenever the message is absent.