go type_error ai_generated true

proto: Marshal 被传入 nil 消息

proto: Marshal called with nil message

ID: go/protobuf-marshal-nil-message

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 95% 成功率
    if msg == nil {
        return errors.New("message is nil")
    }
    b, err := proto.Marshal(msg)
    if err != nil { return err }
  2. 90% 成功率
    func build() (*pb.User, error) {
        return &pb.User{Name: "a"}, nil // never return (*pb.User)(nil), nil
    }

无效尝试

常见但无效的做法:

  1. 85% 失败

    proto.Marshal returns an error rather than panicking; recover does not catch returned errors.

  2. 80% 失败

    The legacy package delegates to the new one and exhibits the same behavior.