gpt4 book ai didi

go - 如何将嵌套的 Struct 转换/转换为 Protobuf?

转载 作者:行者123 更新时间:2023-12-03 10:08:55 33 4
gpt4 key购买 nike

我正在做一个个人项目并第一次使用 Go。我正在使用结构来操作数据并将数据存储在文件中,我使用 proto 作为编码器。
在项目中,我的原型(prototype)定义如下所示:

message AssetPairInfo {
string Altname = 1;
string AssetClassBase = 2;
string Base = 3;
.... Additional fields
}

message AssetPairsResponse {
AssetPairInfo ADACAD = 1;
AssetPairInfo ADAETH = 2;
AssetPairInfo ADAEUR = 3;
... Additional fields
}
我的结构如下所示:
type AssetPairInfo struct {
Altname string `json:"altname"`
AssetClassBase string `json:"aclass_base"`
Base string `json:"base"`
... Additional fields
}

type AssetPairsResponse struct {
ADACAD AssetPairInfo
ADAETH AssetPairInfo
ADAEUR AssetPairInfo
... Additional fields
}
我只包含了每个结构的 3 个定义,但我的结构有 70 多个定义。
我正在寻找一种将 AssetPairsResponse 结构转换为我的 protobuf 的编程方式。鉴于我的 struct 和 protobuf 共享相同的字段(除了额外生成的 protobuf 字段),似乎应该可以这样做。
任何的想法?

最佳答案

作为解决方法,如果模型(您的自定义和原始消息)共享相同的 json 标记名称,您可以解码您的自定义结构,然后编码原始消息。例如:

myModel := model.AssetPairsResponse{
....
}

b, err := json.Marshal(myModel)


myProto := &pb.AssetPairsResponse{}


json.Unmarshal(b, myProto)

关于go - 如何将嵌套的 Struct 转换/转换为 Protobuf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65407336/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com