Installation
Install the protoc-gen-go plugin
The
protoc-gen-go plugin generates Go code from .proto files. Install it and make sure $GOPATH/bin is on your $PATH:Install protoc
Download the prebuilt
protoc binary for your platform from the releases page.Generating code
Useprotoc with --go_out and --go_opt to generate Go source files. The go_package option in your .proto file sets the import path:
addressbook.pb.go in the current directory.
Working with messages
Generated structs have exported fields for each proto field. Use theproto package for marshaling:
Marshaling and unmarshaling
Utility functions
Clone
Create a deep copy of a message:Equal
Compare two messages for equality (field-by-field, ignoring unknown fields by default):Merge
Merge one message into another (non-zero fields insrc overwrite fields in dst):
JSON support
Useprotojson for JSON marshaling that conforms to the canonical protobuf JSON mapping:
Key API reference
proto.Marshal / proto.Unmarshal
Core binary serialization.
proto.Marshal returns []byte. proto.Unmarshal populates an existing message pointer.proto.Clone
Deep-copies a message. The return type is
proto.Message; cast to the concrete type as needed.proto.Equal
Reports whether two messages are equal. Extension fields and unknown fields are included in the comparison.
protojson
google.golang.org/protobuf/encoding/protojson — JSON encoding with canonical field name mapping, EmitUnpopulated, and UseEnumNumbers options.Use accessor methods like
GetName() rather than direct struct field access when writing library code. Accessor methods are nil-safe and return the default value for unset fields.