make用于内建类型(map、slice 和channel)的内存分配
new用于各种类型的内存分配
new(T)分配了零值填充的T类型的内存空间, 并且返回其地址,即一个*T类型的值
内建函数make(T, args)与new(T)有着不同的功能,
make只能创建slice、map和channel,
并且返回一个有初始值(非零)的T类型,而不是*T
本质来讲,导致这三个类型有所不同的原因是指向数据结构的引用在使用前必须被初始化
The way to go
new(T) allocates zeroed storage for a new item of type T and returns its address,
a value of type *T:
it returns a pointer to a newly allocated zero value of type T,
ready for use;
it applies to value types like arrays and structs (see Chapter 10);
it is equivalent to &T{ }
make(T) returns an initialized value of type T;
it applies only to the 3 built-in reference types:
slices, maps and channels (see chapters 8 and 13).
原文地址:https://www.cnblogs.com/allenhaozi/p/8684334.html
时间: 2024-10-23 08:16:22