文件目录
pb文件
syntax="proto3"; //版本号
package mypro; //包名
enum ClassName{ //枚举
class1=0; //标号 必须从 0开始
class2=1;
class3=2;
}
message Student{ //消息,对应于Go的结构体
string name=1; //1:标号,唯一 即可(相当于数据库中的Id,不一定要从1 ,2的顺序依次排列。)
int32 age=2; //必须指定整型的范围,如int32,int64
string address=3;
ClassName cn=4;
}
message Students{
repeated Student person=1; // repeated 修饰,相当于Go中切片
string school=2;
}
package main
import (
"fmt"
"github.com/golang/protobuf/proto"
"test/mypro" //引入的proto的包 , go语言中,一个目录里面的所有文件都应设置成一个包
)
func main() {
s1 := &mypro.Student{} //第一个学生信息
s1.Name = "jz01"
s1.Age = 23
s1.Address = "cq"
s1.Cn = mypro.ClassName_class2 //枚举类型赋值
ss := &mypro.Students{}
ss.Person = append(ss.Person, s1) //将第一个学生信息添加到Students对应的切片中
s2 := &mypro.Student{} //第二个学生信息
s2.Name = "jz02"
s2.Age = 25
s2.Address = "cd"
s2.Cn = mypro.ClassName_class3
ss.Person = append(ss.Person, s2) //将第二个学生信息添加到Students对应的切片中
ss.School = "cqu"
fmt.Println("Students信息为:", ss)
// Marshal takes a protocol buffer message
// and encodes it into the wire format, returning the data.
buffer, _ := proto.Marshal(ss)
fmt.Println("序列化之后的信息为:", buffer)
// Use UnmarshalMerge to preserve and append to existing data.
data := &mypro.Students{}
proto.Unmarshal(buffer, data)
fmt.Println("反序列化之后的信息为:", data)
}
执行go build 或者go run main.go
ubuntu@VM-0-17-ubuntu:~/test$ ./test
Students信息为: person:{name:"jz01" age:23 address:"cq" cn:class2} person:{name:"jz02" age:25 address:"cd" cn:class3} school:"cqu"
序列化之后的信息为: [10 14 10 4 106 122 48 49 16 23 26 2 99 113 32 1 10 14 10 4 106 122 48 50 16 25 26 2 99 100 32 2 18 3 99 113 117]
反序列化之后的信息为: person:{name:"jz01" age:23 address:"cq" cn:class2} person:{name:"jz02" age:25 address:"cd" cn:class3} school:"cqu"