go - 如何动态设置结构成员

标签 go

现在我正在研究 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.. 来完成这项工作。

所以我有问题:
  • 为什么 Code2 中的 ob'member 为零?
  • 有没有办法动态设置 Go 结构的成员对象?
  • 最佳答案

    请看一下这个文档,它讨论了 Go 为 protobufs 生成的代码。 https://developers.google.com/protocol-buffers/docs/reference/go-generated

    您应该能够通过直接访问相应的成员字段(已导出)在生成的代码中设置 protobuf 消息字段。

    关于go - 如何动态设置结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58298488/

    相关文章:

    去虚函数模拟

    go - 需要帮助在 Go 中自动化 TLS 证书处理

    go - 使用 go lang 在 protobuf 中创建数组指针

    go - 以编程方式为 os.Process 编写标准输入

    Golang 数组输入未按预期工作

    go - 如何在 Go 中为内置类型创建别名的文字 slice

    arrays - 同时遍历两个集合

    Go函数点符号

    dictionary - 无法将 map 对象转换为 JSON 对象

    arrays - 有没有更简单的方法在 Go 中解码这个 json?