簡單例子跑通

https://github.com/google/protobuf/blob/master/src/README.md
https://studygolang.com/articles/7394

$ git clone https://github.com/google/protobuf.git
$ cd protobuf
$ git submodule update --init --recursive
$ ./autogen.sh

$ ./configure
$ make
$ make check
$ sudo make install
$ sudo ldconfig # refresh shared library cache.
go get github.com/golang/protobuf
go get github.com/golang/protobuf/protoc-gen-go
cat test.proto
syntax="proto2";
package example;

enum FOO { X = 17; };

message Test {
required string label = 1;
optional int32 type = 2 [default=77];
repeated int64 reps = 3;
optional group OptionalGroup = 4 {
required string RequiredField = 5;
}
}
protoc --go_out=. test.proto
#產生的文件放到$GOPATH中便于引用,這里扔到my.protobuf.test/example
cat test.go
package main

import (
    "fmt"
    "log"
    // 輔助庫
    "github.com/golang/protobuf/proto"

    // test.pb.go 的路徑
    "my.protobuf.test/example"
)

func main() {
    // 創建一個消息 Test
    test := &example.Test{
        // 使用輔助函數設置域的值
        Label: proto.String("hello"),
        Type:  proto.Int32(17),
        Optionalgroup: &example.Test_OptionalGroup{
            RequiredField: proto.String("good bye"),
        },
    }

    fmt.Printf("Label:%s Type:%d\n", test.GetLabel(), test.GetType())

    *(test.Label) = "hello go"
    *(test.Type) = 18

    // 進行編碼
    data, err := proto.Marshal(test)
    if err != nil {
        log.Fatal("marshaling error: ", err)
    }

    fmt.Printf("Binary Len:%d\n", len(data))

    // 進行解碼
    newTest := &example.Test{}
    err = proto.Unmarshal(data, newTest)
    if err != nil {
        log.Fatal("unmarshaling error: ", err)
    }

    fmt.Printf("Label:%s Type:%d\n", test.GetLabel(), test.GetType())

    // 測試結果
    if test.GetLabel() != newTest.GetLabel() {
        log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
    }
}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容