Length and capacity
内置函数len
和cap
接受各种类型的参数并返回类型为int
的结果。该实现确保结果始终可以转换为int
。
Call | Argument type | Result |
---|---|---|
len(s) | string type | string length in bytes |
[n]T, *[n]T | array length (== n) | |
[]T | slice length | |
map[K]T | map length (number of defined keys) | |
chan T | number of elements queued in channel buffer | |
cap(s) | [n]T, *[n]T | array length (== n) |
[]T | slice capacity | |
chan T | channel buffer capacity |
切片的容量是在基础数组中为其分配了空间的元素数。
The built-in functions len
and cap
take arguments of various types and return a result of type int
. The implementation guarantees that the result always fits into an int
.
Call | Argument type | Result |
---|---|---|
len(s) | string type | string length in bytes |
[n]T, *[n]T | array length (== n) | |
[]T | slice length | |
map[K]T | map length (number of defined keys) | |
chan T | number of elements queued in channel buffer | |
cap(s) | [n]T, *[n]T | array length (== n) |
[]T | slice capacity | |
chan T | channel buffer capacity |
The capacity of a slice is the number of elements for which there is space allocated in the underlying array. At any time the following relationship holds:
0
nil
切片,映射或通道的长度为 0 。nil
切片或通道的容量为0。
如果 s
是字符串常量,则表达式len(s)
为常量。
如果 s
的类型是一个数组或者指向了数组的指针,并且表达式 s
不包含 单接收通道 或(非常量)函数调用,则 len(s)
and cap(s)
也是常量,否则 len
和cap
的调用不是常量表达式。
const (
c1 = imag(2i) // imag(2i) = 2.0 是常量
c2 = len([10]float64{2}) // [10]float64{2} 不包含函数调用
c3 = len([10]float64{c1}) // [10]float64{c1} 不包含函数调用
c4 = len([10]float64{imag(2i)}) // imag(2i) 是常量,不会进行函数调用
c5 = len([10]float64{imag(z)}) // 不合法: imag(z) 是 (非常量) 函数调用
)
var z complex128
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。