go
type_error
ai_generated
true
proto: Marshal 被传入 nil 消息
proto: Marshal called with nil message
ID: go/protobuf-marshal-nil-message
80%修复率
87%置信度
0证据数
2024-05-02首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| google.golang.org/protobuf v1.26+ | active | — | — | — |
根因分析
向 proto.Marshal 传入了类型化的 nil proto 消息(如 (*pb.User)(nil)),或将类型化 nil 接口存储后进行了序列化。
English
A typed nil proto message (e.g. (*pb.User)(nil)) was passed to proto.Marshal, or a typed-nil interface was stored and later marshaled.
解决方案
-
95% 成功率
if msg == nil { return errors.New("message is nil") } b, err := proto.Marshal(msg) if err != nil { return err } -
90% 成功率
func build() (*pb.User, error) { return &pb.User{Name: "a"}, nil // never return (*pb.User)(nil), nil }
无效尝试
常见但无效的做法:
-
85% 失败
proto.Marshal returns an error rather than panicking; recover does not catch returned errors.
-
80% 失败
The legacy package delegates to the new one and exhibits the same behavior.