dongzhou1865 2018-02-22 08:43
浏览 40
已采纳

为什么该切片会更改其容量?

I'm new to golang. A Tour of Go has this snippet:

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.
    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
", len(s), cap(s), s)
}

and the result:

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]

My confusion is the cap=4 in the last line - I thought it should remain 6. What is the cause of the capacity changing from 6 to 4 in the last line? Also, why only the last line changes its capacity but the others don't ?

  • 写回答

3条回答 默认 最新

  • dongpuchao1680 2018-02-22 08:46
    关注

    Remember that slice holds data in an array. By dropping first two elements we moved the beginning of the slice to the right and now there are fewer slots between the start of the slice inside the array and the end of the array.

    Droping elements at the end of the slice has no effect on capacity as the distance between start of the slice inside the array and the end of the backing array does not change.

    Neither of the operations modify the backing array, they just modify the slice data.

    See https://blog.golang.org/go-slices-usage-and-internals the observed behaviour is explained in section Slice internals

    By printing the slice header you can see the changes happening

    func printSlice(s []int) {
        sh := (*reflect.SliceHeader)(unsafe.Pointer(&s))
        fmt.Printf("header=%+v len=%d cap=%d %v
    ", sh, len(s), cap(s), s)
    }
    

    In the last call, the data pointer is moved ahead.

    header=&{Data:272990208 Len:6 Cap:6} len=6 cap=6 [2 3 5 7 11 13]
    header=&{Data:272990208 Len:0 Cap:6} len=0 cap=6 []
    header=&{Data:272990208 Len:4 Cap:6} len=4 cap=6 [2 3 5 7]
    header=&{Data:272990216 Len:2 Cap:4} len=2 cap=4 [5 7]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题