摘自"A Go of Go" -为什么该切片会更改其容量? [英] From "A Tour of Go" - Why this slice changes its capacity?

查看:68
本文介绍了摘自"A Go of Go" -为什么该切片会更改其容量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是golang的新手. 围棋之旅包含以下代码段:

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

和结果:

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]

我的困惑是最后一行中的cap=4-我认为应该保持为6.最后一行中容量从6变为4的原因是什么?另外,为什么只有最后一行更改其容量而其他行却不更改?

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 ?

推荐答案

请记住,切片将数据保存在数组中.通过删除前两个元素,我们将切片的开头移到了右侧,现在在数组内部的切片开头和数组结尾之间的插槽减少了.

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.

请参见 https://blog.golang.org/go-slices-usage -and-internals Slice内部原理

通过打印切片标题,您可以看到正在发生的变化

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\n", 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]

这篇关于摘自"A Go of Go" -为什么该切片会更改其容量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆