func main() {
a := append([]int{1, 2, 3, 4}, 1)
fmt.Println(len(a), cap(a))
b := a[1:2:3]
fmt.Println(len(b), cap(b))
b = a[1:2]
fmt.Println(len(b), cap(b))
}
以下为输出结果
5 8
1 2
1 7
得到以下结论:
|
s[low:high] |
从切片s的索引位置low到high处所获得的切片,len=high-low,cap=原slice的cap-low |
|
s[low : high : max] |
从切片s的索引位置low到high处所获得的切片,len=high-low,cap=max-low |
即第三个参数max未指定的情况下,cap=原slice的cap-第一个参数low
本文通过示例解析了Go语言中切片操作的length和capacity计算规则,重点讲解了如何使用索引和步长创建子切片,并揭示了在max参数未指定时cap的计算原理。
1349

被折叠的 条评论
为什么被折叠?



