Go使用protobuf

WIN7 + Go1.9.2+protobuf3.5.1

  

1.首先定义一个用于测试的proto文件test.proto,内容如下:

    syntax = "proto3";
    package example;
        
    message Test {
      string strTest = 1;
      double dTest = 2;
      repeated int64 i64RepsTest = 3;
    }

 

2.需要下载两个exe来生成对应的go文件

https://github.com/google/protobuf/releases下载protoc-3.5.1-win32.zip文件,解压得到protoc.exe

②使用go get github.com/golang/protobuf/protoc-gen-go下载生成go格式代码的插件(默认会下载到GOPATH/bin中,而GOPATH/bin默认是c:/Users/Administrator/go/bin),得到protoc-gen-go.exe

③将protoc.exe、protoc-gen-go.exe和test.proto拷贝到同一个文件夹中

protoc.exe --go_out=. test.proto,生成对应的go代码文件test.pb.go

 

3.下面使用代码

①使用go get github.com/golang/protobuf/proto安装protobuf库

②将生成的test.pb.go拷贝到项目中(这里必须注意,因为使用了package example,所以必须在项目中新建example文件夹再拷贝进去)

③在项目中使用protobuf库,以及引入Test

import (
    "github.com/golang/protobuf/proto"
    "../example" //这里根据项目结构决定example的位置
)

 

④测试代码(在这里测试了中文字符串,double数据以及int64的数据)

        marshalTest := &example.Test{
            *proto.String("test_string中文test"),
            *proto.Float64(2.34),
            []int64{123456789123, 4, 5}}

        data, err := proto.Marshal(marshalTest)
        if err != nil {
            fmt.Println("proto.Marshal err : ", err)
        }

        unmarshalTest := &example.Test{}
        err = proto.Unmarshal(data, unmarshalTest)

        if err != nil {
            fmt.Println("proto.Unmarshal err : ", err)
        }

        fmt.Println("strTest = ", unmarshalTest.GetStrTest())
        fmt.Println("doubleTest = ", unmarshalTest.GetDTest())
        for _, v := range unmarshalTest.GetI64RepsTest() {
            fmt.Println("int64 reps = ", v)
        }

输出的结果

以上。

 

参考博文:《golang使用protobuf》

 

PS:protobuf相关

cocos2dx 3.x 集成protobuf

转载于:https://www.cnblogs.com/chevin/p/8444698.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值