Golang and Protocol Buffer

Jimmy (xiaoke) Shen
1 min readSep 18, 2020

--

Run the following command to install the Go protocol buffers plugin:

go install google.golang.org/protobuf/cmd/protoc-gen-go

Generate a simple file based on [1] and name it as addressbook.proto

Run the following command

mkdir OUTPUT
protoc -I=./ --go_out=./OUTPUT ./addressbook.proto

You will get an automatically generated file named addressbook.pb.go in the OUTPUT folder

It is too long, I will not copy everything here. Just part of the important will be shown

const (
Person_MOBILE Person_PhoneType = 0
Person_HOME Person_PhoneType = 1
Person_WORK Person_PhoneType = 2
)
type Person struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Id int32 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` // Unique ID number for this person.
Email string `protobuf:"bytes,3,opt,name=email,proto3" json:"email,omitempty"`
Phones []*Person_PhoneNumber `protobuf:"bytes,4,rep,name=phones,proto3" json:"phones,omitempty"`
LastUpdated *timestamp.Timestamp `protobuf:"bytes,5,opt,name=last_updated,json=lastUpdated,proto3" json:"last_updated,omitempty"`
}
// Our address book file is just one of these.
type AddressBook struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
People []*Person `protobuf:"bytes,1,rep,name=people,proto3" json:"people,omitempty"`
}

You can compare and learn what has been generated. More details, please follow [1].

About protocol buffer

See [2]

Reference

[1] https://developers.google.com/protocol-buffers/docs/gotutorial

[2] https://medium.com/better-programming/understanding-protocol-buffers-43c5bced0d47

--

--

No responses yet