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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM