Search code examples
goprotocol-buffers

How to serialize a Go map into a protobuff


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<string, string> Fields = 2;
}

Go marshal:

func MarshalNote(n *remember.Note) ([]byte, error) {
    return proto.Marshal(&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.


Solution

  • 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