2
0

More than 3 years have passed since last update.

Goのnew()とmake()の違い

Posted at

new()とmake()の違いが分からなかったので調べてみた

比較

new(T) make()
対象 任意の型 slice,map,channelのみ
初期化 初期化しない(ゼロ値になる) 初期化する
返り値 *T T

makeとnewを使い分ける理由

makeについて

  • slice,map,channelが隠蔽されたデータ構造への参照であり、このデータ構造が使用前に初期化されている必要がある
  • slice,map,channelの内部データ構造を初期化し、使用可能となるよう値を準備する

newについて

  • 他言語におけるnew()と基本的に同じ
  • 型Tの新しいアイテム用にゼロ化した領域を割り当てそのアドレスである*T型の値を返す
  • 新しく割り当てられた型Tのゼロ値ポインタを返す

参考

http://golang.jp/tag/effective-go/page/2
https://cipepser.hatenablog.com/entry/go-new-make

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