From the course: gRPC in Go

Writing .proto file

From the course: gRPC in Go

Start my 1-month free trial

Writing .proto file

- [Instructor] Let's start looking at how to write the protocol buffers definition file. So we have Ride struct, which has an ID, a DriverID, which are both strings, Location, which is another struct, this one with the latitude and longitude, and then PassengerIDs, which is a slice of strings, Start and End time, and Distance, which is float64, and then a type which is a RideType, which is defined here as either Regular or Pool ride. Now let's have a look at the protocol buffer definitions. So we are going to write only the StartRequest, the start of a ride is going to have only part of the fields from the whole Ride struct that we saw. So we get a string, we say the type first, then the name in lowercase, and then the field number. So string id equal one, driver_id, location repeated which means zero or more of strings and this is going to be translated to a slice in in GO. Protocol buffers timestamp, and the RideType. The RideType here is an enum, which must start with a zero, so I'm starting zero with UNSET and then REGULAR and POOL. If you look at the location, it has a double type. We do not have doubles in GO. There is a mapping between protocol buffer types to GO types and you can see that double goes to a float64 in GO. The field numbers are for forward compatibility. When we are renaming a field, for example, in protocol buffers, we do not rename the field. We create a new field with a new name, with a number which is bigger than the last one. So for example, if you want to change the id, we're going to put another field here called maybe ride id and then give it the number seven. And then when we are going to create these messages, they're going to be backward compatible. If you have something which has the zero value, protocol buffer is not even going to serialize it. So there is a zero overhead for keeping these old fields around and we are backward compatible with older messages.

Contents