问题描述
golang中切片的len和len有什么区别?
What is the difference between cap and len of a slice in golang?
根据定义:
切片既有长度又有容量.
A slice has both a length and a capacity.
切片的长度是其包含的元素数量.
The length of a slice is the number of elements it contains.
切片的容量是底层数组中元素的数量,从切片中的第一个元素开始计数.
The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.
x := make([]int, 0, 5) // len(b)=0, cap(b)=5
len仅表示非空值吗?
Does the len mean non null values only?
推荐答案
切片是一种抽象,它在幕后使用了一个数组.
A slice is an abstraction that uses an array under the covers.
cap len
caplen
Go中的slice抽象非常好,因为它将为您调整基础数组的大小,此外,由于Go中的数组无法调整大小,因此几乎总是使用slice.
The slice abstraction in Go is very nice since it will resize the underlying array for you, plus in Go arrays cannot be resized so slices are almost always used instead.
示例:
s := make([]int, 0, 3)
for i := 0; i < 5; i++ {
s = append(s, i)
fmt.Printf("cap %v, len %v, %p\n", cap(s), len(s), s)
}
将输出如下内容:
cap 3, len 1, 0x1040e130
cap 3, len 2, 0x1040e130
cap 3, len 3, 0x1040e130
cap 6, len 4, 0x10432220
cap 6, len 5, 0x10432220
append
append
我意识到您并没有询问数组和追加,但是它们对于理解切片和内建原因非常基础.
I realize you did not ask about arrays and append but they are pretty foundational in understanding the slice and the reason for the builtins.
这篇关于在golang中的cap与len切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!