golang中make函数阅读理解
golang有很多内置函数,今天开看一下 用得比较多的 make 函数:
这里是官方源码的注释:
// 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
谷歌翻译(狗头求不被喷):
make内置函数分配并初始化slice,map或chan类型的对象(仅)。
像new一样,第一个参数是类型,而不是值。 与new不同,make的返回类型与其参数的类型相同,而不是指向它的指针。 结果的规格取决于类型:
切片:大小指定长度。
切片的容量等于其长度。 可以提供第二个整数参数来指定不同的容量。 它必须不小于长度。 例如,make([] int,0,10)分配一个大小为10的基础数组,并返回一个长度为0且容量为10的切片,该切片由该基础数组支持。
映射:为空的映射分配足够的空间以容纳指定数量的元素。 该大小可以省略,在这种情况下,分配的起始大小较小。
通道:使用指定的缓冲区容量初始化通道的缓冲区。 如果为零或忽略大小,则通道不缓冲。
我自己的操作:
首先是对 slice切片的操作:
func TestMake(t *testing.T) {
// 测试 slice
sli := make([]int, 0, 10)
fmt.Println(sli)
}
输出结果:
=== RUN TestMake
[]
--- PASS: TestMake (0.00s)
PASS
Process finished with exit code 0
然后改为:
func TestMake(t *testing.T) {
// 测试 slice
sli := make([]int, 1, 10)
fmt.Println(sli)
}
输出结果:
=== RUN TestMake
[0]
--- PASS: TestMake (0.00s)
PASS
Process finished with exit code 0
清晰明了, make函数的第一个参数是要实例的对象, 第二个参数是 长度, 第三个参数 如果类型是slice, 则对应的是容量大小.
make函数会根据第一个参数给 slice 初始化对应个数的 0 值,而只有容量(也就是第二个参数的时候), 默认是一个有大小的空的slice.
待续...