Protobuf definition
- Go course
- Advanced
- Lesson 38/68
- 4 min
Learn to define messages with a .proto file.
Protobuf definition
In gRPC the contract is written in a .proto file: messages (data structures) and a service (callable methods).
syntax = "proto3";
package selam;
option go_package = "example.com/app/selampb";
message SelamIstek { string ad = 1; }
message SelamYanit { string mesaj = 1; }
service Selamlayici {
rpc Selam(SelamIstek) returns (SelamYanit);
}Field numbers (= 1) are the field's identity in the binary encoding.
Types and repeated fields
Protobuf types map directly to Go: string → string, int32 → int32, bool → bool. A repeated field becomes a slice and a nested message a pointer:
message Sepet {
string sahip = 1;
repeated string urunler = 2; // []string
}When removing a field, marking its number reserved prevents accidental reuse.
Practice Message counterpart
Write the Go counterpart of message Sepet { string sahip = 1; repeated string urunler = 2; } by hand: type Sepet struct { Sahip string; Urunler []string }. Print the number of products for Sepet{"ada", []string{"kalem", "defter"}}.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Sepet struct {
Sahip string
Urunler []string
}
func main() {
s := Sepet{"ada", []string{"kalem", "defter"}}
fmt.Println(len(s.Urunler))
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is changing a field number in a published message dangerous?
- It has no effect
- Old clients decode the data into the wrong field Correct answer
- The message gets bigger
- Compilation slows down
Explanation: The binary format sends the number, not the name; if it changes, old and new code interpret the data differently.
2 List field
message Siparis {
____ string urunler = 1;
}
message Siparis {
repeated string urunler = 1;
}
Explanation: The repeated keyword makes a field a list; it becomes []string in Go.
3 proto and Go
| Term | Meaning |
|---|---|
string ad = 1 |
Ad string |
repeated int32 puan = 2 |
Puan []int32 |
message |
struct |
service |
Interface |