go runtime_error ai_generated true

panic: runtime error: invalid memory address or nil pointer dereference in proto.Unmarshal

ID: go/proto-nil-pointer-deref-unmarshal

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

Version Compatibility

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

Root Cause

proto.Unmarshal was called with a nil message pointer, or a generated message's internal fields were not initialized (e.g., using a zero-value struct literal instead of a constructor).

generic

中文

调用 proto.Unmarshal 时传入了 nil 消息指针,或生成消息的内部字段未初始化(例如使用零值结构体字面量而非构造函数)。

Workarounds

  1. 95% success
    msg := &pb.User{}
    if err := proto.Unmarshal(data, msg); err != nil { return err }
  2. 90% success
    msg := pb.NewUser() // or &pb.User{} then reset
    if err := proto.Unmarshal(data, msg); err != nil { return err }

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Swallowing the panic leaves the message nil; subsequent field access panics again and corrupts control flow.

  2. 80% fail

    proto.Unmarshal requires a proto.Message (pointer receiver); passing a value fails to compile or operates on a copy.