试图更好地了解切片的行为

问题描述

当我阅读Go中的片段时,它们似乎足够合理。 我知道切片结构具有基于基础数组的容量和当前包含的元素的长度,而且切片还引用了下面的数组。

但是,当我玩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)的第一次和第二次呼叫之间发生变化?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)