Go 的 new() 和 make() 关于零值的疑问

在 effective go 里写道:

new

https://golang.org/doc/effect...

does not initialize the memory,it only zeros it

make

https://golang.org/doc/effect...

It creates slices, maps, and channels only, and it returns an initialized (not zeroed) value of type T (not *T)

意思大概是:

new : allocate memory + zero it
make : allocate memory + initialize memory

我的疑问是:

Q1 : alloate memory 我能理解,initialize memory 是什么意思?

Q2 : 如上面写的 new zero it,但 make not zeroed,这个说法准确吗?好像仅 effective go 里提到了这个 zero 操作的区别,其他关于 new 和 make 区别的文章里都没有提到。

阅读 3.7k
2 个回答

new:

In Go terminology, it returns a pointer to a newly allocated zero value of type T.

new 返回一个指针,指向的对象是 zero value 。map slice channel 的 zero value 是 nil。

make 返回一个相应类型的对象(不是指针),这个对象一定不是 nil 。

new是新建一个类型的指针的变量,new(User)相当于&User{},创建的指针指向的对象属性全部是零值。
make是创建一个指定类型(仅map、chan、slice支持make)变量,参数指定了对象的类型和容量以及长度,并进行了对象的初始化操作。

make([]int, 3)       // slice len=3 cap=3
make([]int, 0, 3)    //slice len=9 cap=3
make(chan int, 3)    // chan 容量3
make(map[int]int, 3) // map 容量3

其中Ptr类型变量比较简单就一个地址数值;而Slice、Chan、Map类型变量是相对复杂一些拥有很多属性,在make时会根据参数执行一些初始化操作,例如分配长度需要空间。

new -> Ptr
make -> Slice Map Chan

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题