Salient Points for Protocol Buffers

Simply Explained (for Golang)

How to start .proto file?

Without the line above, the complier for protocol buffer will assume the syntax is based on proto2.

Specify Field Types

All fields are scalar type: string, float, int32, int64, uint32, uint64, sint32, sint64, fixed32 (always 4 bytes), fixed64 , bool, string, bytes etc.

Notice the use of underscore as convention for the field names. You can also have multiple message types in the same .proto file. Notice message name starts in big cap.

Default values

Composite Types — Enum

Every enum definition must contain a constant that maps to zero as its first element. This is so that the default value aforementioned can work.

If the same enum constants are used in other enum definition, you need the line: option allow_alias = true;

Including Maps in definitions

Handling removal of fields

When you remove a field, you need to prevent the field numbers from being reused. What you need to do is to create reserved fields to “block” these field numbers. If not done, when other reuse the field numbers, severe compatibility can result.

Nesting other message types

Other messages can be included as field types i.e. nested. For example:

Here, the repeated keywork ensures you can use other messages as field types inside your message.

More nesting…

You can fall in love with nesting deeply :P


Importing .proto files

To help in nesting, you can import definitions from other .proto files

The protocol compiler searches for imported files in a set of folders specified on the protocol CLI using the flag,

Placeholder .proto file

Imagine if you need to move your .proto file to a new file location. All your other .proto files importing the .proto file will need to be updated with a new import line. That will be a lot of work. Is there a better way?

To save the day, you can use the “import public” syntax such as —

new proto file:

old proto file to be modified:

other proto file using bar.proto:

Oneof fields

If you have mutiple fields in a message and at most one field will be set at the same time, you can enforce filling one field by using the oneof feature.

Defining Services in .proto file

Compiling to .pb.go

In go, the protobuf go compiler generates .pb.go file with a type for each message type in your file.

Generating your classes in go

GRPC support in go

If you are using grpc, you also need to generate the grpc go files with an additioanl flag of “ go-grpc_out=.”

Above example generates the file into the relative folder of ./chunky



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store