make和new的区别
文章v2版
作用对象
make 只能用于slice,chan,map 对这些对象进行初始化
new 用于 golang任意type 自定义类型和 内置数据类型
语义
make(T,args) 初始化内置数据结构(slice,chan,map)
new(T) 根据传入的类型,分配一片零值的内存空间,并返回指向这片内存空间的指针 value *T ,显示的创建了对象的一个指针,而不必使用&T对获取该对象的地址。
官方
Allocation with new
Go has two allocation primitives, the built-in functions
new
andmake
. They do different things and apply to different types, which can be confusing, but the rules are simple. Let’s talk aboutnew
first. It’s a built-in function that allocates memory, but unlike its namesakes in some other languages it does not initialize the memory, it only zeros it. That is,new(T)
allocates zeroed storage for a new item of typeT
and returns its address, a value of type*T
. In Go terminology, it returns a pointer to a newly allocated zero value of typeT
.
核心意思:new不会初始化内存,new(T)只是分配一个零值的存储空间,并返回指向该空间的一个地址,这个值的类型*T
,
Allocation with make
Back to allocation. The built-in function
make(T,
args)
serves a purpose different fromnew(T)
. It creates slices, maps, and channels only, and it returns an initialized (not zeroed) value of typeT
(not*T
). The reason for the distinction is that these three types represent, under the covers, references to data structures t