Arrays 为什么切片的容量在变化?不应该';不一样吗?
我是个新手,这个例子让我感到困惑:Arrays 为什么切片的容量在变化?不应该';不一样吗?,arrays,go,slice,Arrays,Go,Slice,我是个新手,这个例子让我感到困惑: import "fmt" func main() { s := []int{2, 3, 5, 7, 11, 13} printSlice(s) // Slice the slice to give it zero length. s = s[:0] printSlice(s) // Extend its length. s = s[:4] printSlice(s)
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
// Slice the slice to give it zero length.
s = s[:0]
printSlice(s)
// Extend its length.
s = s[:4]
printSlice(s)
// Drop its first two values.
s = s[2:]
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
输出:
len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]
为什么在最后一次中容量变为4?根据定义,容量是基础数组的长度。片的容量是基础数组中的元素数,从片中的第一个元素开始计算
在您的示例中,在最后一种情况下,切片的起始元素是5,而在底层arrray({2,3,5,7,11,13})中,5的泊松是2。要计算容量,应从索引2开始计算。如果从该位置开始计数,您将获得正确的容量4切片构建在阵列上,它由指向阵列的指针、段的长度及其容量(段的最大长度)组成 关键点是
段
,而不是数组
s=s[2:]
当您删除前两个值时,s
成为指向数组另一半段的切片,从第三个元素开始,因此它的上限为4
正如您不能通过s[-1]
指向数组的前一部分一样,该部分也不能计入cap
ref:明白了,现在有意义了。我将把切片看作是对数组段的引用,而不是对整个数组的引用。