How to serialize a Go map into a protobuff

huangapple go评论83阅读模式
英文:

How to serialize a Go map into a protobuff

问题

我正在遵循这个教程,并到达了关于将Go结构体序列化/编组为协议缓冲区的部分。我的结构体中有一个映射(map),但我找不到任何关于如何处理映射的编组的文档。

以下是我想要序列化的Fields map[string]string

Go结构体:

type Note struct {
    ID     NoteID
    Fields map[string]string
}

协议缓冲区模式:

package internal;

message Note {
    optional int64 ID = 1;
    optional map<string, string> Fields = 2;
}

Go编组:

func MarshalNote(n *remember.Note) ([]byte, error) {
    return proto.Marshal(&Note{
        ID: proto.Int64(int64(n.ID))
        Fields: proto.???
    })
}

我不知道最后一行该怎么做,我搜索到的所有内容都是关于将字段映射到协议缓冲区模式,而不是关于将映射映射到协议缓冲区模式。

英文:

I'm following this tutorial and got to the part on serializing/marshaling Go structs into a protocol buffer. My struct has a map and I can't find any documentation on how to handle marshaling a map.

In the following I want to serialize Fields map[string]string:

Go struct:

type Note struct {
	ID     NoteID
	Fields map[string]string
}

protobuf schema:

package internal;

message Note {
	optional int64 ID = 1;
	optional map&lt;string, string&gt; Fields = 2;
}

Go marshal:

func MarshalNote(n *remember.Note) ([]byte, error) {
	return proto.Marshal(&amp;Note{
		ID: proto.Int64(int64(n.ID))
		Fields: proto.???
	})
}

I have no idea what to do for the last line and anything I search for talks about mapping a field to a protobuf scheme, and not about mapping a map to a protobuf scheme.

答案1

得分: 1

protobuf 是一个定义明确的序列化格式,使用它的好处之一是它可以根据 protobuf 模式为您生成所有的数据结构(在您喜欢的编程语言中)。

英文:

protobuf is a well defined serialization format and one of the benefits of use it is that generates all the data structures for you(on your favorite language) just using the protobuf schema

huangapple
  • 本文由 发表于 2016年12月19日 11:22:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/41215340.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定