在golang中的cap与len切片 [英] cap vs len of slice in golang

查看:101
本文介绍了在golang中的cap与len切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 告诉您数组中有多少个项目.

cap tells you the capacity of the underlying array. len tells you how many items are in the array.

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 将返回容量更大的新切片.在第4次迭代中,您将注意到更大的容量和新的指针地址.

As you can see once the capacity is met, append will return a new slice with a larger capacity. On the 4th iteration you will notice a larger capacity and a new pointer address.

播放示例

我意识到您并没有询问数组和追加,但是它们对于理解切片和内建原因非常基础.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆