Go 中 new
和 make
都是用来内存分配和值初始化的方法。
1. new 返回类型的指针
new
的作用是计算类型大小,为其分配零值内存。new
可以初始化任一类型。new
返回的是指针*T
。
例如,下面的代码:
t := new(T)
等同于:
var temp T
t := &temp
通常情况下,我们很少会用到 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
2. make 返回类型的值
make
的作用是分配类型和初始化成员结构。make
只接收 slice、map、channel 参数。make
返回的是该类型的值T
。
make
的使用方式如下:
Call | Type T | Result |
---|---|---|
make(T, n) | slice | 类型 T 的切片,长度 n,容量 n |
make(T, n, m) | slice | 类型 T 的切片,长度 n,容量 m |
make(T) | map | 类型 T 的 map |
make(T, n) | map | 类型 T 的 map,容量 n |
make(T) | channel | 类型 T 的无缓冲通道 |
make(T, n) | channel | 类型 T 的缓冲通道,容量 n |
// 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
3. 类型的零值
类型的零值:
类型 | 零值 |
---|---|
Booleans | false |
Numeric types | |
Strings | "" |
Pointers,functions,interfaces,slices,channels,and maps | nil |