在"帽QUOT; Golang的 [英] The "cap" of Golang
问题描述
下面去$ C $ C:
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))
为什么帽(片)
等于 4
?
我曾经以为这应该是 2
。
推荐答案
numbers4 [4:6:8]
是的整片前pression :
有关的阵列,指针阵列,或切片 A
(但不是一个串),主前pression
For an array, pointer to array, or slice
a
(but not a string), the primary expression
a[low : high : max]
构造相同类型的片,并与相同长度和元素的简单的片前pression A [低:高]
。此外,它的将其设置为最大控制所产生的切片的能力 - 低
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
.
该规范说,整片前pression控制能力,限制了最大 - 低
,而你的情况是 8 - 4 = 4
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
这篇关于在"帽QUOT; Golang的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!