You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Protobuf类型未实现protoreflect.ProtoMessage错误的解决方法

问题描述

我有一个导入了google/protobuf/any.proto的Protobuf消息:

message MintRecord {
    ...
    google.protobuf.Any data = 11;
    ...
}

我尝试使用anypb将另一个Protobuf序列化到data字段中:

data, err := anypb.New(protobuf.LootcratePrize{
    Items: &protobuf.Inventory{Items: items},
    Roll:  fmt.Sprintf("%f", roll),
})
if err != nil {
    log.Println("[Lootbox] Err: error marshalling lootcrate prize data into mintRec", err)
} else {
    mintRecordProto.Data = data
}

编译时出现以下错误:

cannot use protobuf.LootcratePrize{…} (value of type protobuf.LootcratePrize) as type protoreflect.ProtoMessage in argument to anypb.New:
    protobuf.LootcratePrize does not implement protoreflect.ProtoMessage (ProtoReflect method has pointer receiver)

根据文档我的操作没问题,请问该如何解决?

附要序列化的Protobuf定义(Lootcrate.proto):

syntax = "proto3";

package protobuf;
option go_package = "protobuf/";

import "protobuf/inventory.proto";
import "protobuf/flowerdbservice.proto";

message LootcratePrize {
    Inventory items = 1;
    repeated NFT flowers = 2;
    string roll = 3;
}
解决方法

错误原因是anypb.New要求参数实现protoreflect.ProtoMessage接口,而该接口的ProtoReflect方法是指针接收器实现的——只有*protobuf.LootcratePrize类型才符合接口要求,值类型不满足。

只需要给传入anypb.New的结构体值加取地址符&,改成指针类型即可:

data, err := anypb.New(&protobuf.LootcratePrize{
    Items: &protobuf.Inventory{Items: items},
    Roll:  fmt.Sprintf("%f", roll),
})

这样编译就能通过,因为*LootcratePrize指针类型已实现protoreflect.ProtoMessage接口。

内容的提问来源于stack exchange,提问作者P A S H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 11:55:24