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

如何将结构转换/转换为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条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效