Work with the Generated Code

Distributed Services with Go — by Travis Jeffery (21 / 84)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Compile Protocol Buffers | TOC | What You Learned 👉

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​ { ​//…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.