gpt4 book ai didi

arrays - 当容量减少时, slice 的行为如何?

转载 作者:IT王子 更新时间:2023-10-29 02:32:27 25 4
gpt4 key购买 nike

我已经读过this blog post .每一个解释都是那么清晰易懂。我明白了当 slice 的容量增加时它们是如何起作用的。但我对这种行为的反面有疑问。当容量减少时, slice 的行为如何?考虑这个例子:

var numbers = [8]int{1, 11, 78, 81, 101, 344, 65, 13}
fmt.Printf("len=%d, cap=%d\n", len(numbers), cap(numbers)) // len=8, cap=8

numbers2 := numbers[:4]
fmt.Printf("len=%d, cap=%d\n", len(numbers2), cap(numbers2)) // len=4, cap=8

对于 numbers2 来说很明显。新创建的数组的容量将设置为新 slice 中元素数量的两倍。但是考虑到这个例子,它的行为有所不同:

numbers3 := numbers[1:5]
fmt.Printf("len=%d, cap=%d\n", len(numbers3), cap(numbers3)) // len=4, cap=7

numbers4 := numbers[3:8]
fmt.Printf("len=%d, cap=%d\n", len(numbers4), cap(numbers4)) // len=5, cap=5

我想知道这有什么意义?有没有合适的容量计算公式,比如递增?

最佳答案

slice 规则在 Spec: Slice expressions 中描述。 .

在您的示例中,numbers 是一个 array .当您对数组进行 slice 时,生成的 slice 的容量将是从生成的 slice 的第一个元素到数组的最后一个元素的元素数。当你 slice slice ,结果的容量是从第一个元素到原始 slice 容量的元素个数。

因此 numbers2 := numbers[:4],low 索引被省略,因此默认为 0,因此结果的容量为 8 - 0 = 8(numbers 数组的大小)。

numbers3 := numbers[1:5] 中,结果的容量为 7,因为结果中的第一个元素位于索引 1,所以 8 - 1 = 7

numbers4 := numbers[3:8] 中,容量将为 8 - 3 = 5

注意:这是当您使用“简单” slice 表达式时,即您在 slice 表达式中仅提供 2 个索引(其形式为 a[low : high ])。还有一个“完整” slice 表达式,其形式为 a[low : high : max],它通过将结果设置为 max - low 来额外控制结果 slice 的容量>。

查看相关问题:

Go slices - capacity/length?

Go slice length is capacity -1, why?

Slicing: Out of bounds error in Go

Slices in Go: why does it allow appending more than the capacity allows?

关于arrays - 当容量减少时, slice 的行为如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44862762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com