drjyvoi734793 2019-07-16 19:49
浏览 796
已采纳

如何将结构转换/转换为Protobuf?

I am working on a personal project & using Go for the first time. I am using structs for operating on the data and for storing the data in a file, I am using proto as the encoder.

In the project, my proto definition looks something like this

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

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

and my struct looks like this

type KVData struct {
    Key       string
    Value     string
}

Currently, this is how I am creating proto data

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

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

What I am looking for is a way to do this:

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
}

I tried googling but couldn't find any solution explaining how to do this.

Note, I am not just trying to solve this specific case, I also want to know what's the recommended Go way to operate between structs and proto(use only proto?)?

  • 写回答

2条回答 默认 最新

  • drmy1050 2019-07-16 21:09
    关注

    You cannot, at least not in Go 1.12.7.

    Go's Protobuf compiler adds 3 extra fields to each struct generated from a message:

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

    Therefore your struct and generated one have different fields and are not identical as per, therefore not assignable.

    If two structs differ only in the tags, it is possible to 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
    

    You have to create a new struct instance manually.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 鼠标右键,撤销删除 复制 移动,要怎样删除
  • ¥15 使用MATLAB进行余弦相似度计算加速
  • ¥15 服务器安装php5.6版本
  • ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
  • ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题
  • ¥15 我想在WPF的Model Code中获取ViewModel Code中的一个参数
  • ¥15 arcgis处理土地利用道路 建筑 林地分类
  • ¥20 使用visual studio 工具用C++语音,调用openslsx库读取excel文件的sheet问题
  • ¥100 寻会做云闪付tn转h5支付链接的技术
  • ¥15 DockerSwarm跨节点无法访问问题