当我阅读 Go 中的 slice 时,它们似乎很合理。我知道切片结构的容量基于底层数组和当前包含的元素的长度,切片也引用了下面的数组。
但是,当我在玩 Go 的“A Tour of Go”时,我不明白为什么以下内容会降低底层数组的容量。
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
s = s[1:5]
printSlice(s)
s = s[:0]
printSlice(s)
s = s[0:5]
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=4 cap=5 [3 5 7 11]
len=0 cap=5 []
len=5 cap=5 [3 5 7 11 13]
为什么第一次和第二次调用之间的容量会发生变化printSlice(s)?
慕沐林林
慕田峪7331174
哈士奇WWW
随时随地看视频慕课网APP
相关分类