5
2

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 3 years have passed since last update.

Marshalの本当の意味知ってる?

Posted at

背景

Go言語を触っていると、よく構造体をJSONに変換するために以下のように Marshal という関数を使いますよね。何気なく使っていていましたが、Marshal の意味とは何か知りたくなったので調べてみました。

json.Marshal使用例
type Person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	p := Person{
		Name: "hoge",
		Age: 30,
	}
	s, err := json.Marshal(p)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(s))
}

Marshaling とは

まずはWikipediaからの情報です。

In computer science, marshalling or marshaling (US spelling) is the process of transforming the memory representation of an object into a data format suitable for storage or transmission.

Google翻訳をかけると、Marshalingとは、
オブジェクトのメモリ表現をストレージまたは送信に適したデータ形式に変換するプロセスです。

上記のプログラム例で言うと、
「オブジェクトのメモリ表現」が Person構造体であるp
「送信に適したデータ形式」が JSON形式
ということになります。

結論

Marshal とは、JSON形式に変換することではなく、あくまでも「オブジェクトのメモリ表現を送信に適したデータ形式に変換する」ということです。

参考

5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?