A minimalist guide to ProtoBuf

Have you heard of Protocol Buffers? It’s like XML or JSON, but smaller, faster, and simpler!

Rei
Published in
6 min readSep 13, 2021

--

What are Protocol Buffers?

Protocol Buffers (Protobuf) is a free and open-source cross-platform library used to serialize structured data.

That means it’s like XML or JSON, but smaller, faster, and simpler.

Define your data structure and let protoc generate all the code for you!

MOTIVATION

(Lower is better)

In this article, we will learn

  1. How to define ProtoBuf?
  2. How to generate the code?

Part 1: How to Define ProtoBuf?

First of all, you need to create a proto file and add syntax = “proto3”; to the first line.

Note: If you don’t add the line to the fist line protobuf will define as proto2 which is old version of protobuf

Some Rules

  • Data types can be user-defined enums or other messages
  • Field names are not important, ProtoBuf only looks after tags.
  • Tags don’t need to be in-order or sequential (but highly recommended)
  • Tags must be unique for same-level fields
  • You can define nested messages
syntax = “proto3”;// Structuremessage UpperCamelCase {
<data-type> lower_snake_case = tag;
}
// Examplemessage MyUser {
string full_name = 1;
int32 age = 2;
bool is_married = 3;
repeated string friends = 4;
repeated Book books = 5;
enum Sex {
NONE = 0; // default
MALE = 1;
FEMALE = 2;
}
Sex sex = 6;
message Address {
...
}
Address address = 7;
map<string, Project> projects = 3;
...
}
message Book {
...
}
message Project {
...
}

--

--