golang——win10环境protobuf的使用

1、protobuf配置

(1)https://github.com/protocolbuffers/protobuf/releases

(2)选择适合的版本:protoc-3.8.0-win64.zip

(3)解压后将文件 protoc.exe 所在目录添加到环境变量 Path

(4)检查protobuf版本,CMD命令窗口执行:protoc --version

2、proto文件处理

(1)获取相关库

go get -u github.com/golang/protobuf/protoc-gen-go

(2)编写test.proto文件

//指定版本
syntax = "proto3";
//包名
package pb;
//课程
message Course{
    int32 id = 1;
    string name = 2;
}
//学生
message Student{
    int32 id = 1;
    string name = 2;
    repeated Course courses = 3;
}

(3)生成文件命令:protoc --go_out=. test.proto

命令执行完,会在test.proto同级目录下生成test.pb.go文件

3、使用

package main

import (
	"fmt"
	"log"
	"test/protobuf/pb"

	"github.com/golang/protobuf/proto"
)

func main() {
	course1 := pb.Course{
		Id:   *proto.Int32(1),
		Name: *proto.String("Golang"),
	}
	course2 := pb.Course{
		Id:   *proto.Int32(2),
		Name: *proto.String("Python3"),
	}
	stu := pb.Student{
		Id:      *proto.Int32(1),
		Name:    *proto.String("笃志弘毅"),
		Courses: []*pb.Course{&course1, &course2},
	}
	//序列化
	data, err := proto.Marshal(&stu)
	if err != nil {
		log.Fatalln("proto.Marshal err:", err)
	}
	fmt.Println(data)
	//反序列化
	var stuNew pb.Student
	err = proto.Unmarshal(data, &stuNew)
	if err != nil {
		log.Fatalln("proto.Unmarshal err:", err)
	}
	fmt.Println(stuNew)
}

// 输出
// [8 1 18 12 231 172 131 229 191 151 229 188 152 230 175 133 26 10 8 1 18 6 71 111 108 97 110 103 26 11 8 2 18 7 80 121 116 104 111 110 51]
// {1 笃志弘毅 [id:1 name:"Golang"  id:2 name:"Python3" ] {} [] 0}
笃志:“博学而笃志,切问而近思,仁在其中矣。”
弘毅:“士不可以不弘毅,任重而道远。”
止于至善:“大学之道,在明明德,在亲民,在止于至善。”
关注:笃志弘毅,止于至善
原文地址:https://www.cnblogs.com/dzhy/p/11100504.html