Files
the-way-to-go_ZH_CN/eBook/07.4.md
Unknown ee65c4cf95 07.3
2014-11-05 18:12:28 -05:00

2.0 KiB
Raw Blame History

7.4 切片重组

175

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

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

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

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

将slice扩展1位可以这么做 sl = sl[0:len(sl)+1]

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

示例 7.11 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 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

另一个例子:

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

问题 7.7

  1. 如果a是一个slice那么s[n:n]的长度是多少?

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

##链接