Go语言中new跟make是内置函数,主要用来创建分配类型内存。

new( )

new(T)创建一个没有任何数据的类型为T的实例,并返回该实例的指针;

源码解析

1
2
3
func new
func new(Type) *Type
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.

make( )

make(T, args)只能创建 slice、map和channel,并且返回一个有初始值args(非零)的T类型的实例,非指针。

源码解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func make
func make(Type, size IntegerType) Type
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, so make([]int, 0, 10) allocates a slice of length 0 and
capacity 10.
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.

二者异同

二者都是内存的分配(堆上),但是make只用于slice、map以及channel的初始化(非零值);而new用于类型的内存分配,并且内存置为零。所以在我们编写程序的时候,就可以根据自己的需要很好的选择了。

make返回的还是这三个引用类型本身;而new返回的是指向类型的指针。

交流沟通:QQ群866437035
在这里插入图片描述