Go语言中new与make的比较
go语言new()与make()的区别对于初入golang的开发者来说是个容易混淆的点,这里尝试对这两个的区别做一些总结。
官方文档
首先查找官方文档中的描述,首先是关于’new()‘的:
1// The new built-in function allocates memory. The first argument is a type,
2// not a value, and the value returned is a pointer to a newly
3// allocated zero value of that type.
4func new(Type) *Type
关于’make()’:
1// The make built-in function allocates and initializes an object of type
2// slice, map, or chan (only). Like new, the first argument is a type, not a
3// value. Unlike new, make's return type is the same as the type of its
4// argument, not a pointer to it. The specification of the result depends on
5// the type:
6// Slice: The size specifies the length. The capacity of the slice is
7// equal to its length. A second integer argument may be provided to
8// specify a different capacity; it must be no smaller than the
9// length, so make([]int, 0, 10) allocates a slice of length 0 and
10// capacity 10.
11// Map: An empty map is allocated with enough space to hold the
12// specified number of elements. The size may be omitted, in which case
13// a small starting size is allocated.
14// Channel: The channel's buffer is initialized with the specified
15// buffer capacity. If zero, or the size is omitted, the channel is
16// unbuffered.
17func make(t Type, size ...IntegerType) Type
new() vs make()
new() | make() | |
---|---|---|
定义 | 为需要创建的数据类型分配内存,返回一个指向分配内存的指针 | 为需要创建的slice/map/chan类型分配资源并初始化 |
输入 | 一个参数,指定需要创建的数据类型 | 多个参数,不同类型又专有意义 |
输出 | 指针 | 数据 |
使用场景 | 任意类型 | 只能用于slice/map/chan类型数据 |
new()的使用说明
1var s3 = new([]int)
2*s3 = append((*s3), 0, 1)
3fmt.Println(s3)
输出如下:
&[0 1]
make()的使用说明
类型 | 说明 | 参数解释 |
---|---|---|
slice | 创建一个指定长度的slice | 第一个参数(t):所要创建的类型,例如[]int第二个参数(size):指定slice的长度第三个参数(可选):如果指定了这个参数,那么它说明了要创建的slice的容量(capacity),并且这个参数必须大于等于size |
map | 创建一个空的map,并且为map预留足够的空间可以存放size个元素 | 第一个参数(t):指定要创建的类型,此处为map第二个参数(size):指定map大小,让make预留出至少size个元素所需要的空间 |
channel | 创建一个channel,并为这个channel初始化一个长度为size的buffer | 第一个参数:指定channel类型,例如chan string第二个参数(size):指定缓冲区的大小 |
1var slice1 []int = make([]int, 10, 20)
2var slice2 = make([]int, 10, 20)
3
4var map1 map[int]string = make(map[int]string, 10)
5var map2 = make(map[int]string, 10)
6
7var chan1 chan string = make(chan string, 1024)
8var chan2 = make(chan string, 1024)