11
6

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 Buffers の Marshal と Unmarshal の小さなサンプル

Posted at

小さいサンプルです。
Marshal と Unmarshal は同じファイル構成で、 main.go のロジック切り替えで違いを見てみます。

参考にした公式ページはこちらです。
Protocol Buffer Basics: Go

$ tree
.
├── main.go
└── person
    ├── person.pb.go
    └── person.proto
syntax = "proto3";

package person;

message Person {
  string Name = 1;
}
$ protoc -I=./person --go_out=./person ./person/person.proto

Marshal

インスタンスを byte へ。

main.go
package main

import (
	"fmt"
	"github.com/golang/protobuf/proto"
	pb "github.com/mochizukikotaro/study-proto-marshal/person"
)

func main() {
	p := &pb.Person{
		Name: "yuki",
	}
	data, _ := proto.Marshal(p)
	fmt.Println(data)
}
$ go run main.go
[10 4 121 117 107 105]

Unmarshal

byte からインスタンスを。

main.go
package main

import (
	"fmt"
	"github.com/golang/protobuf/proto"
	pb "github.com/mochizukikotaro/study-proto-marshal/person"
)

func main() {
	p := &pb.Person{}
	proto.Unmarshal([]byte{10, 4, 121, 117, 107, 105}, p)
	fmt.Println(p)
}
$ go run main.go
Name:"yuki"

以上となります。

11
6
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
11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?