57

[Go - note] go中new和make分配变量的区别

 4 years ago
source link: https://studygolang.com/articles/25715
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

New

与其他语言中的同名方法不同是,go中的new不会初始化内存,而仅仅是赋予零值,也就是说返回一个新分配的类型的零值的指针(*T)。这样创建的变量可以不用进一步初始化就可以直接使用。

但有时需要初始化为非零值则可以用composite literal方式。

filed name 可根据是否需要按key:value 方式填写。

new(File)`and`&File{}`

是相同的表达

Make

make只用来创建slice, map, 和channel,并且返回的初始化的值(T)

而非零值(*T),因为这几种类型的都需要初始化才能使用。

make([]int, 10, 100)

返回的是length 10 , capacity100的slice, 而new([]int)返回一个指向零值的slice。

下面的例子可以看出区别

var p *[]int = new([]int)       // allocates slice structure; \*p == nil; rarely useful
var v  []int = make([]int, 100) // the slice v now refers to a new array of 100 ints

// Unnecessarily complex:
var p *[]int = new([]int)
*p = make([]int, 100, 100)

// Idiomatic:
v := make([]int, 100)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK