• 7.4 切片重组(reslice)
    • 链接

    7.4 切片重组(reslice)

    我们已经知道切片创建的时候通常比相关数组小,例如:

    1. slice1 := make([]type, start_length, capacity)

    其中 start_length 作为切片初始长度而 capacity 作为相关数组的长度。

    这么做的好处是我们的切片在达到容量上限后可以扩容。改变切片长度的过程称之为切片重组 reslicing,做法如下:slice1 = slice1[0:end],其中 end 是新的末尾索引(即长度)。

    将切片扩展 1 位可以这么做:

    1. sl = sl[0:len(sl)+1]

    切片可以反复扩展直到占据整个相关数组。

    示例 7.11 reslicing.go

    1. package main
    2. import "fmt"
    3. func main() {
    4. slice1 := make([]int, 0, 10)
    5. // load the slice, cap(slice1) is 10:
    6. for i := 0; i < cap(slice1); i++ {
    7. slice1 = slice1[0:i+1]
    8. slice1[i] = i
    9. fmt.Printf("The length of slice is %d\n", len(slice1))
    10. }
    11. // print the slice:
    12. for i := 0; i < len(slice1); i++ {
    13. fmt.Printf("Slice at %d is %d\n", i, slice1[i])
    14. }
    15. }

    输出结果:

    1. The length of slice is 1
    2. The length of slice is 2
    3. The length of slice is 3
    4. The length of slice is 4
    5. The length of slice is 5
    6. The length of slice is 6
    7. The length of slice is 7
    8. The length of slice is 8
    9. The length of slice is 9
    10. The length of slice is 10
    11. Slice at 0 is 0
    12. Slice at 1 is 1
    13. Slice at 2 is 2
    14. Slice at 3 is 3
    15. Slice at 4 is 4
    16. Slice at 5 is 5
    17. Slice at 6 is 6
    18. Slice at 7 is 7
    19. Slice at 8 is 8
    20. Slice at 9 is 9

    另一个例子:

    1. var ar = [10]int{0,1,2,3,4,5,6,7,8,9}
    2. var a = ar[5:7] // reference to subarray {5,6} - len(a) is 2 and cap(a) is 5

    将 a 重新分片:

    1. a = a[0:4] // ref of subarray {5,6,7,8} - len(a) is now 4 but cap(a) is still 5

    问题 7.7

    1) 如果 a 是一个切片,那么 s[n:n] 的长度是多少?

    2) s[n:n+1] 的长度又是多少?

    链接

    • 目录
    • 上一节:For-range 结构
    • 下一节:切片的复制与追加