go语言new()与make()的区别对于初入golang的开发者来说是个容易混淆的点,这里尝试对这两个的区别做一些总结。
官方文档
首先查找官方文档中的描述,首先是关于’new()‘的:
1
2
3
4
|
// 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()’:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
// 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.
func make(t Type, size ...IntegerType) Type
|
new() vs make()
|
new() |
make() |
定义 |
为需要创建的数据类型分配内存,返回一个指向分配内存的指针 |
为需要创建的slice/map/chan类型分配资源并初始化 |
输入 |
一个参数,指定需要创建的数据类型 |
多个参数,不同类型又专有意义 |
输出 |
指针 |
数据 |
使用场景 |
任意类型 |
只能用于slice/map/chan类型数据 |
new()的使用说明
1
2
3
|
var s3 = new([]int)
*s3 = append((*s3), 0, 1)
fmt.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):指定缓冲区的大小 |
1
2
3
4
5
6
7
8
|
var slice1 []int = make([]int, 10, 20)
var slice2 = make([]int, 10, 20)
var map1 map[int]string = make(map[int]string, 10)
var map2 = make(map[int]string, 10)
var chan1 chan string = make(chan string, 1024)
var chan2 = make(chan string, 1024)
|