[Go] 使用protobuf进行序列化和反序列化
先定义消息类型
orders.proto
syntax = "proto2"; package message; message Orders { required int32 order_id=1; required string title=2; }
在GOPATH创建目录和编译这个消息类型输出到该目录,包名是message
mkdir $GOPATH/src/message;protoc --go_out $GOPATH/src/message orders.proto
编写go文件进行序列化和反序列化刚才生成的包里的类型结构体数据
package main import "message" import "github.com/golang/protobuf/proto" import "fmt" func main() { orders := &message.Orders{ OrderId: proto.Int32(1), Title: proto.String("第一个订单"), } //序列化成二进制数据 ordersBytes, _ := proto.Marshal(orders) //反序列化二进制数据 twoOrders := &message.Orders{} proto.Unmarshal(ordersBytes, twoOrders) fmt.Println(twoOrders.GetTitle()) fmt.Println(twoOrders.GetOrderId()) }
相关推荐
Erick 2020-06-17
Erick 2020-06-17
Charlesbases 2020-04-16
mitesi 2020-04-07
Erick 2020-11-17
Charlesbases 2020-10-23
Erick 2020-08-21
mitesi 2020-06-07
Charlesbases 2020-06-07
zagnix 2020-06-04
小小书童 2020-05-20
gumingyaotangwei 2020-05-17
极品小肥羊 2020-04-23
极品小肥羊 2020-04-20
higher0 2020-03-09
Erick 2020-03-08
Erick 2020-02-03
Erick 2020-02-03