Golang-make和new的区别|Go主题月

802 阅读2分钟

值类型和引用类型

值类型:int,float,bool,string,struct和array。变量直接存储值,分配栈区的内存空间,这些变量所占据的空间在函数被调用完后会自动释放 引用类型:slice,map,chan和值类型对应的指针。变量存储的是一个地址(或者理解为指针),指针指向内存中真正存储数据的首地址。内存通常在堆上分配,通过GC回收。

对于引用类型的变量,不仅要声明这个变量,还要手动为其分配空间。make和new都在堆上分配内存。

New
// The new built-in function allocates memory. The first argument is a type,
// not a value, and the value returned is a pointer to a newly
// allocated zero value of that type.
func new(Type) *Type

该方法的参数要求传入一个类型,而不是一个值,它会申请一个该类型大小的内存空间,并会初始化为对应的零值,返回该类型的指针类型。

Make
// The make built-in function allocates and initializes an object of type
// slice, map, or chan (only). Like new, the first argument is a type, not a
// value. Unlike new, make's return type is the same as the type of its
// argument, not a pointer to it. The specification of the result depends on
// the type:
//	Slice: The size specifies the length. The capacity of the slice is
//	equal to its length. A second integer argument may be provided to
//	specify a different capacity; it must be no smaller than the
//	length. For example, make([]int, 0, 10) allocates an underlying array
//	of size 10 and returns a slice of length 0 and capacity 10 that is
//	backed by this underlying array.
//	Map: An empty map is allocated with enough space to hold the
//	specified number of elements. The size may be omitted, in which case
//	a small starting size is allocated.
//	Channel: The channel's buffer is initialized with the specified
//	buffer capacity. If zero, or the size is omitted, the channel is
//	unbuffered.
func make(t Type, size ...IntegerType) Type

make入参指定slice, map, chan类型,只为这些类型申请内存。可以看到返回的是该类型的实例,而不是指针。

切片:第二个参数len,第三个是cap,cap不能小于len

map:会根据size大小分配资源,以足够存储size个元素。如果入参没有写size,会默认分配一个小的起始size

通道:对于chan,size表示缓冲区的大小。如果入参没有写size,channel为无缓冲channel

总而言之:new是申请一块内存,而make返回一个类型的初始值。