我正在处理一个个人项目并第一次使用 Go。我使用结构来操作数据并将数据存储在文件中,我使用 proto 作为编码器。
在项目中,我的原型定义如下所示:
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 字段),似乎应该可以这样做。
有什么想法吗?
答案 0 :(得分:2)
作为解决方法,如果模型(您的自定义消息和 proto 消息)共享相同的 json 标记名称,您可以解组自定义结构,然后编组 proto 消息。例如:
myModel := model.AssetPairsResponse{
....
}
b, err := json.Marshal(myModel)
myProto := &pb.AssetPairsResponse{}
json.Unmarshal(b, myProto)