Golang的”cap”

huangapple go评论95阅读模式
英文:

The "cap" of Golang

问题

以下是要翻译的内容:

以下是Go代码:

var numbers4 = [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
slice := numbers4[4:6:8] 
fmt.Printf("%d\n", cap(slice))

为什么cap(slice)等于4

我曾经以为应该是2

英文:

The following go code:

var numbers4 = [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
slice := numbers4[4:6:8] 
fmt.Printf("%d\n", cap(slice))

Why is cap(slice) equal to 4?

I used to thought that should be 2.

答案1

得分: 4

numbers4[4:6:8] 是一个完整的切片表达式

> 对于数组、数组指针或切片 a(但不包括字符串),主表达式
>
> a[low : high : max]
>
> 构造了一个与简单切片表达式 a[low : high] 具有相同类型、长度和元素的切片。此外,它通过将结果切片的容量设置为 max - low控制结果切片的容量

规范中指出,完整的切片表达式控制容量,将其限制为 max - low,在你的例子中为 8 - 4 = 4

容量不是切片可以扩展的“额外”元素,容量是切片可以扩展到的最大长度,包括当前长度 + 超出长度的额外元素。

slice := numbers4[4:6:8]

len(slice) = 6 - 4 = 2
cap(slice) = 8 - 4 = 4
英文:

numbers4[4:6:8] is a full slice expression:

> For an array, pointer to array, or slice a (but not a string), the primary expression
>
> a[low : high : max]
>
> constructs a slice of the same type, and with the same length and elements as the simple slice expression a[low : high]. Additionally, it controls the resulting slice's capacity by setting it to max - low.

The spec says the full slice expression controls the capacity, limiting it to max - low, which in your case is 8 - 4 = 4.

The capacity is not the "extra" elements of which the slice may be extended, the capacity is the max length to which a slice may be extended, which includes current length + extra elements beyond the length.

slice := numbers4[4:6:8]

len(slice) = 6 - 4 = 2
cap(slice) = 8 - 4 = 4

答案2

得分: 3

容量是底层数组中的元素数量(从切片指针所指向的元素开始计算)。

来自Go切片:用法和内部原理

基本上,它意味着容量(cap)不等于长度(len)。
因此,该切片从#4开始,结束于#8,因此容量(cap)为8 - 4 = 4

英文:

> The capacity is the number of elements in the underlying array
> (beginning at the element referred to by the slice pointer).

from Go Slices: usage and internals.

Basically, it means cap != len.
So, the slice starts at #4, and finishes at #8, hence, cap is 8 - 4 = 4.

huangapple
  • 本文由 发表于 2016年3月24日 19:52:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/36199537.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定