new和make的区别是什么
相同点:
- 在GO语言中new和make都是对内存的分配(堆)
不同点:
- new可用于系统默认的数据类型,还可用于自定义的类型;make只用于Slice、MaP及Channel的初始化 【实测用new代替make无报错,但使用时得注意new返回的是指针】
- new为类型申请一片内存空间并返回指向内存的指针; make主要用于创建Slice、MaP及Channel,返回这三个类型本身
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
这里有一个需要注意的问题是: 声明完指针要对指针赋值或者分配地址,否则会报 panic: runtime error: invalid memory address or nil pointer dereference 的错误。这时就可以用new来分配内存地址
**切记new返回的是指针类型**
# 声明一个int型指针
i := new(int)
make
make返回类型。因为make初始化非零,Slice和Channel需要指定长度,但是Map不需要
func make(t Type, size ...InntergerType) 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 onthe 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.
result := make([]string, len(STRUCT))
result := make(map[string][]string)