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
相关产品推荐
相关产品推荐

