标签:Go语言 切片 slice print 开头 nts 输出 fir 二次
package main
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.
fmt.Println(s[:5])
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 [] [2 3 5 7 11] len=4 cap=6 [2 3 5 7] len=2 cap=4 [5 7]
第一次重新赋值s的指向底层数组的0 第二次s还是指向0 第三次指向了2 一切都以开头的那个指向的index 开始切片的 cap就是当前切片的0指向的位置开始到end
如果不理解可以看下图

标签:Go语言 切片 slice print 开头 nts 输出 fir 二次
原文地址:https://www.cnblogs.com/shenwenlong/p/9400359.html