现在我正在研究 GO RPC,我正在使用 gRPC+Protobuf。我关注 openconfig的数据结构,所以我不能重新设计。
我需要填充 protobuf 结构并对其进行编码并将其发送出去,然后客户端将对其进行解码并读取数据。
我的 protobuf 文件(xxx.pb.go) 很复杂,例如,就像这样:
type ObjBase struct {
a *ObjChildAlice,
b *ObjChildBob,
... // there are many variables like ObjChildCheer, ObjChildDog ...
}
type ObjChildAlice struct {
child *ObjChildChild,
}
type ObjChildBob struct {
child *ObjChildChild,
}
// there are many types like ObjChildCheer, ObjChildDog ...
type ObjChildChild {
int i,
}
在服务器端,我需要填写
ObjBase
并将其发送出去,这是我的任务:// Code 1
func () {
init ob with ObjBase
if DataBase has Alice {
fill ob.a with ObjChildAlice
}
if DataBase has Bob {
fill ob.a with ObjChildBob
}
// there are many if..else.. DataBase has Cheer...
return ob
}
所以我先这样编码:
// Code 2
func () {
ob := new(ObjBase)
oba := new(ObjChildAlice)
obb := new(ObjChildBob)
if DataBase has Alice {
ob.a = oba
}
if DataBase has Bob {
ob.b = obb
}
...
return ob
}
但是这段代码不能工作,因为我检查 ob.a 和 ob.b 的成员都是零。
所以我这样改变:
// Code 3
func () {
if DataBase has Alice && DataBase has Bob {
ob := &ObjBase{
a: &ObjChildAlice{},
b: &ObjChildBob{},
}
} else if DataBase has Alice && NOT DataBase has Bob {
ob := &ObjBase{
a: &ObjChildAlice{},
}
} else if ...
return ob
}
这行得通。但是在数据库中,有各种各样的变量,如 Alice、Bob、Cheer、Dog……不可能使用 if..else.. 来完成这项工作。
所以我有问题:
最佳答案
请看一下这个文档,它讨论了 Go 为 protobufs 生成的代码。 https://developers.google.com/protocol-buffers/docs/reference/go-generated
您应该能够通过直接访问相应的成员字段(已导出)在生成的代码中设置 protobuf 消息字段。
关于go - 如何动态设置结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58298488/