go runtime_error ai_generated true

panic: proto: message is nil

ID: go/protobuf-nil-pointer-unmarshal

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.x active — — —

Root Cause

proto.Unmarshal or proto.Marshal was called with a nil message pointer, e.g. var m *pb.User; proto.Unmarshal(data, m). The generated methods dereference the pointer and panic.

generic

中文

proto.Unmarshal 或 proto.Marshal 被传入了 nil 消息指针,例如 var m *pb.User; proto.Unmarshal(data, m)。生成的方法解引用该指针并 panic。

Workarounds

  1. 95% success
    Always allocate with m := &pb.User{} or m := new(pb.User) before Unmarshal: proto.Unmarshal(data, m).
  2. 88% success
    Use proto.Clone or a constructor helper that guarantees a non-nil pointer, and add a staticcheck/errcheck rule to catch nil pointer args.

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Recovering hides a programming bug and returns a zero-value message that downstream logic treats as valid data.

  2. 85% fail

    The panic occurs on the call itself, before any error is returned, so the check never runs.