Go 如何动态设置结构成员
现在我正在研究GO RPC,我正在使用gRPC+Protobuf。我遵循的是公司的数据结构,因此无法重新设计 我需要填充protobuf结构并封送它,然后客户端将解封并读取数据 例如,我的protobuf文件(xxx.pb.go)很复杂,如下所示:Go 如何动态设置结构成员,go,Go,现在我正在研究GO RPC,我正在使用gRPC+Protobuf。我遵循的是公司的数据结构,因此无法重新设计 我需要填充protobuf结构并封送它,然后客户端将解封并读取数据 例如,我的protobuf文件(xxx.pb.go)很复杂,如下所示: type ObjBase struct { a *ObjChildAlice, b *ObjChildBob, ... // there are many variables like ObjChildCheer, ObjCh
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,
}
// 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
}
在服务器端,我需要填写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的成员都是零
所以我改变如下:
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,
}
// 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、Chee、Dog。。。如果……否则……是不可能使用的。。做这项工作
所以我有问题:
请看一下这个文档,它讲述了protobufs的Go生成代码
您应该能够通过直接访问相应的成员字段(已导出)在生成的代码中设置protobuf消息字段。新建(T)和
&T{}
之间没有区别。很难告诉您伪代码有什么问题。举一个小例子。引用一位智者的话:不要试图在围棋中模仿继承。这会造成伤害。new
有一些有效的用例,但99%的时候,最好创建一个文本(ob:=&ObjBase{}
)。