我们已经知道切片创建的时候通常比相关数组小,例如:
其中 start_length
作为切片初始长度而 capacity
作为相关数组的长度。
这么做的好处是我们的切片在达到容量上限后可以扩容。改变切片长度的过程称之为切片重组 reslicing,做法如下:slice1 = slice1[0:end]
,其中 end 是新的末尾索引(即长度)。
将切片扩展 1 位可以这么做:
切片可以反复扩展直到占据整个相关数组。
reslicing.go
输出结果:
The length of slice is 1
The length of slice is 2
The length of slice is 3
The length of slice is 4
The length of slice is 5
The length of slice is 6
The length of slice is 7
The length of slice is 8
The length of slice is 9
The length of slice is 10
Slice at 0 is 0
Slice at 1 is 1
Slice at 2 is 2
Slice at 3 is 3
Slice at 4 is 4
Slice at 5 is 5
Slice at 6 is 6
Slice at 7 is 7
Slice at 8 is 8
Slice at 9 is 9
另一个例子:
将 a 重新分片: