go runtime_error ai_generated true

panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV]

ID: go/grpc-protobuf-oneof-nil-pointer

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-07-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.1 active

Root Cause

Accessing a protobuf oneof field without checking if it is set, leading to nil pointer dereference.

generic

中文

访问protobuf oneof字段而未检查是否已设置,导致空指针解引用。

Workarounds

  1. 98% success Check if oneof field is non-nil before type assertion.
    if v := msg.GetPayload(); v != nil {
        switch x := v.(type) {
        case *pb.Payload_Text:
            fmt.Println(x.Text)
        }
    }
  2. 85% success Use proto.GetField to safely retrieve oneof values.
    import "google.golang.org/protobuf/proto"
    field := proto.GetField(msg, "payload")

Dead Ends

Common approaches that don't work:

  1. Use a type switch without nil check. 95% fail

    Oneof interface can be nil; type switch panics.

  2. Assume the oneof is always populated. 90% fail

    Unmarshal may leave it nil if field is absent.