go runtime_error ai_generated true

panic: proto: Marshal called with nil

ID: go/protobuf-nil-message-marshal

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
google.golang.org/protobuf v1.28+ active

Root Cause

proto.Marshal was called with a nil message pointer, typically after a function returned (nil, nil) or an uninitialized struct field.

generic

中文

使用 nil 消息指针调用 proto.Marshal,通常是因为某函数返回了 (nil, nil) 或结构体字段未初始化。

Workarounds

  1. 92% success
    Guard against nil before marshaling:
    if msg == nil { return errors.New("nil message") }
    b, err := proto.Marshal(msg)
  2. 90% success
    Fix the producer function to never return (nil, nil):
    func build() (*pb.Msg, error) {
      if bad { return nil, errBad }
      return &pb.Msg{...}, nil
    }

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Hides the bug; the caller still receives garbage or a swallowed error.

  2. 70% fail

    Masks the real problem (nil constructor) and may send semantically empty data.