我们已经知道切片创建的时候通常比相关数组小,例如:
slice1 := make([]type, start_length, capacity)
其中 start_length
作为切片初始长度而 capacity
作为相关数组的长度。
这么做的好处是我们的切片在达到容量上限后可以扩容。改变切片长度的过程称之为切片重组 reslicing,做法如下:slice1 = slice1[0:end]
,其中 end 是新的末尾索引(即长度)。
将切片扩展 1 位可以这么做:
sl = sl[0:len(sl)+1]
切片可以反复扩展直到占据整个相关数组。
reslicing.go
package main
import "fmt"
func main() {
slice1 := make([]int, 0, 10)
// load the slice, cap(slice1) is 10:
for i := 0; i < cap(slice1); i++ {
slice1 = slice1[0:i+1]
slice1[i] = i
fmt.Printf("The length of slice is %d\n", len(slice1))
}
// print the slice:
for i := 0; i < len(slice1); i++ {
fmt.Printf("Slice at %d is %d\n", i, slice1[i])
}
}
输出结果:
The length of slice is1The length of slice is2The length of slice is3The length of slice is4The length of slice is5The length of slice is6The length of slice is7The length of slice is8The length of slice is9The length of slice is10Slice at 0is0Slice at 1is1Slice at 2is2Slice at 3is3Slice at 4is4Slice at 5is5Slice at 6is6Slice at 7is7Slice at 8is8Slice at 9is9
另一个例子:
var ar = [10]int{0,1,2,3,4,5,6,7,8,9}
var a = ar[5:7] // reference to subarray {5,6} - len(a) is 2 and cap(a) is 5
将 a 重新分片:
a = a[0:4] // ref of subarray {5,6,7,8} - len(a) is now 4 but cap(a) is still
5