Writing your first message in Protocol Buffers
2 December, 2022
4
4
0
Contributors
💭 Let's Recall
Source: https://grpc.io/docs/what-is-grpc/introduction/
✍️ Declaring a message
proto2
and proto3
. So we need to specify which proto version we are using in the first line of the proto file.message
. You can think of a message like a class.<type> <variable-name> = <field-numbers>;
Note: If a field value is not set during the creating of an object they will either be kept empty or have a default value after serialisation.
🧰 Type support in proto3
Number
•
int32
, int64
, sint32
, sint64
.•
uint32
, uint64
.•
fixed32
, fixed64
, sfixed32
, sfixed64
.•
float
, double
.int32
and int64
uses variable-length encoding i.e they might have different lengths in the serialized output.fixed32
, fixed64
the length is fixed.sint32
, sint64
than int
's.Boolean
bool
. It can have values true
or false
.String
string
. It can have arbitrary length and the default value is an empty string.Note: A string must always contain UTF-8 encoded or 7-bit ASCII text, and cannot be longer than 232
Bytes
byte
, when we have raw data inside the message like an image. Just like string, in the case of bytes, the default value is empty bytes.🔢 Field Numbers
Note: Once you have used a message a particular field number you cannot change the field numbers. This will result in the old data getting invalidated. For example, if for the field name
you used the number 2 but later on changed it to the number 3, the new deserialiser won't be able to deserialise the old data.
1
. The field numbers in the range 1
through 15
take one byte to encode. Field numbers in the range 16
through 2047
take two bytes. So reserve the 1-15 numbers for important fields that won't be changing and will be frequently occurring.🔁 Repeated Fields
repeated
keyword to specify that.hobbies
in our User
message. Then we can do that by:Enunmerations (or Enums)
RED
, GREEN
, BLUE
, etc.enum
.•
0
, unlike the field numbers which we saw can have a minimum value of 1.•
Nested Types
Conclusion
tutorials
tutorial
handsontutorial
develevate