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

标签 go struct protocol-buffers proto

我正在做一个个人项目并且是第一次使用 Go。我使用结构对数据进行操作并将数据存储在文件中,我使用 proto 作为编码器。

在项目中,我的原型(prototype)定义看起来像这样

message Data {
    string key = 1;
    string value = 2;
}

message Record {
    int64 size = 1;
    Data data = 2;
}

我的结构看起来像这样

type KVData struct {
    Key       string
    Value     string
}

目前,这就是我创建原型(prototype)数据的方式

kvData := KVData{Key: "name", Value: "A"}

record := &pb.Record{
        Size: 20,
        Data: &pb.Data{Key: "name", Value: "A"},
}

我正在寻找一种方法来做到这一点:

record := &pb.Record{
        Size: 20,
        Data: &((pb.Data)kvData), // Won't work
}

// or like Python

record := &pb.Record{
        Size: 20,
        Data: &(pb.Data{**kvData}), // Won't work
}

我尝试使用谷歌搜索,但找不到任何解释如何执行此操作的解决方案。

请注意,我不只是想解决这个具体案例,我还想知道推荐的在结构和原型(prototype)之间操作的 Go 方式是什么(只使用原型(prototype)?)?

最佳答案

你不能,至少在 Go 1.12.7 中不能。

Go 的 Protobuf 编译器为从消息生成的每个结构添加了 3 个额外的字段:

XXX_NoUnkeyedLiteral         struct{} `json:"-"`
XXX_unrecognized             []byte   `json:"-"`
XXX_sizecache                int32    `json:"-"`

因此,您的struct 和生成的结构具有不同的字段并且不完全相同,因此不是assignable .

如果两个结构仅在标签上不同,则有可能 convert it :

type Person struct {
    Name    string
    Address *struct {
        Street string
        City   string
    }
}

var data *struct {
    Name    string `json:"name"`
    Address *struct {
        Street string `json:"street"`
        City   string `json:"city"`
    } `json:"address"`
}

var person = (*Person)(data)  // ignoring tags, the underlying types are identical

您必须手动创建一个新的 struct 实例。

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

相关文章:

go - gccgo -static 与 -static-libgo

c - 在结构中分配动态数组

java - 如何在 Ruby 和 Java 之间序列化/解析 protobuf 对象?

c++ - FlatBuffers/Protobuf 中是否有支持任意 24 位带符号整数定义的可移植二进制序列化模式?

GO (Golang) vendor 实验在 mac osx 上失败

c# - 标准 xml 解析器在 Golang 中的性能非常低

c++ - VexCL 结构 vector ?

双重访问查找操作所需的结构的 C++ 容器

protocol-buffers - Protocol Buffer - 用例

php - http 将 url 部分路由到不同的服务器