0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

個人メモ:Protocol Buffers3_golangで使ってみる

Last updated at Posted at 2019-10-05

golangで、作ったprotobufを呼んで見る

フォルダ構成

prootbufTest
|-- go
|  -- protoTest.go
|-- protobuf
|  -- Student.proto

golang用のprotobuf作成

①protobuf作成

cd \protobuf
ファイル名:Student.proto

syntax ="proto3";

message Student {
    string name = 1;
    int32 age = 2;
}

②コンパイルし、Student.pb.goを生成

protoc --go_out=./ Student.proto

protobuf参照用のgolangプログラム作成

cd ../go
ファイル名:protoTest.go

package main

import (
	"練習/protobuf"
	"fmt"
	"github.com/golang/protobuf/proto"
)

func main() {
	text := &Student.Student{
		Name:    "protobufTest",
		Age:20,
	}

	fmt.Println("Student情報:",text)
	// proto Marshal
	data, err := proto.Marshal(text)
	if err != nil {
		return
	}

	fmt.Println("proto Marshal後:",data)

	Stu01 := &Student.Student{}

	//	proto Unmarshal
	err = proto.Unmarshal(data, Stu01)
	if err != nil {
		return
	}
	fmt.Println("proto Unmarshal後:",Stu01)
	fmt.Println("Unmarshal後の名前取得:",Stu01.Name)
	fmt.Println("GetNameでの名前取得:",Stu01.GetName())
}

実行結果

Student情報: name:"protobufTest" age:20 
proto Marshal後: [10 12 112 114 111 116 111 98 117 102 84 101 115 116 16 20]
proto Unmarshal後: name:"protobufTest" age:20 
Unmarshal後の名前取得: protobufTest
GetNameでの名前取得: protobufTest

Process finished with exit code 0
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?