Work with the Generated Code

Although the generated code in log.pb.go is a lot longer than your handwritten code in log.go (because of the extra code needed to marshal to the protobuf binary wire format), you’ll use the code as if you’d handwritten it. For example, you’ll create instances using the & operator (or new keyword) and access fields using a dot.

The compiler generates various methods on the struct, but the only methods you’ll use directly are the getters. Use the struct’s fields when you can, but you’ll find the getters useful when you have multiple messages with the same getter(s) and you want to abstract those method(s) into an interface. For example, imagine you’re building a retail site like Amazon and have different types of stuff you sell—books, games, and so on—each with a field for the item’s price, and you want to find the total of the items in the user’s cart. You’d make a Pricer interface and a Total function that takes in a slice of Pricer interfaces and returns their total cost. Here’s what the code would look like:

 type​ Book ​struct​ {
  Price ​uint64
 }
 
 func​(b *Book) GetPrice() ​uint64​ { ​// ... }
 
 type​ Game ​struct​ {
  Price ​uint64
 }
 
 func​(b *Game) GetPrice() ​uint64​ { ​// ... }
 
 type​ Pricer ​interface​ {
  GetPrice() ​uint64
 }
 
 func​ Total(items []Pricer) ​uint64​ { ​// ... }

Now imagine that you want to write a script to change the price of all your inventory—books, games, and so on. You could do this with reflection, but reflection should be your last resort since, as the Go proverb goes, reflection is never clear.[12] If we just had setters, we could use an interface like the following to set the price on the different kinds of items in your inventory:

 type​ PriceAdjuster ​interface​ {
  SetPrice(price ​uint64​)
 }

When the compiled code isn’t quite what you need, you can extend the compiler’s output with plugins. Though we don’t need to write a plugin for this project, I’ve written some plugins that were incredibly useful to the projects I worked on; it’s worth learning to write your own so you can recognize when a plugin will save you a ton of manual labor.