What is the purpose of capacity in make() of go language?

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

What is the purpose of capacity in make() of go language?

问题

我正在学习Go语言,并对切片中的容量感到困惑。

例如 arr := make([]float64, 5, 10),我有一个包含5个值的数组,其容量为10。如果我将一个值分配给第8个位置,编译器会抛出索引超出范围的错误。如果我扩展一个切片,它会创建一个新的切片(请参考我从官方Go语言文档中复制的内容)。

这是切片的文档:

“切片不会复制切片的数据。它创建一个指向原始数组的新切片值。”
“要增加切片的容量,必须创建一个新的、更大的切片,并将原始切片的内容复制到其中。”

那么容量的目的是什么?

谢谢。

英文:

I'm learning golang, and confused about the capacity in slice.
For example arr := make([]float64, 5, 10)
I have an array of 5 values, and its capacity is 10. If I assign a value to 8th position, the compiler would throw an error index is out of range. If I grow a slice, but it creates a new slice (see the doc that I copied from the official go language).

Here's the slice doc:

"Slicing does not copy the slice's data. It creates a new slice value that points to the original array."
"To increase the capacity of a slice one must create a new, larger slice and copy the contents of the original slice into it. "

So what's the purpose of capacity?

Thanks

答案1

得分: 14

一个切片有三个部分:指向底层数组的指针、长度和容量。长度是根据程序逻辑确定的数组长度,容量是底层数组的实际长度。

容量在重新分配之前是固定的。只要最终长度不超过容量,你可以随时更改长度。例如,你可以使用arr[:7]将数组长度设置为7,但容量仍然是10。如果你使用arr[:11],会出现错误,因为在不重新分配的情况下无法扩展切片到那么大。

你可以阅读这篇文章,了解更详细的切片讨论:
http://blog.golang.org/go-slices-usage-and-internals

英文:

A slice has three parts. A pointer to an underlying array, a length, and a capacity. The length is the length of the array according to program logic and capacity is the true length of the underlying array.

The capacity is fixed without reallocating. The length can be changed whenever you want as long as the final length doesn't exceed the capacity. In this case you can do arr[:7] and your array will be length 7 but still capacity 10. If you do arr[:11], you will get an error because you can't grow the slice that large without reallocating.

You may want to read this for a more in depth discussion of slices:
http://blog.golang.org/go-slices-usage-and-internals

huangapple
  • 本文由 发表于 2015年2月21日 02:56:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/28636235.html
匿名

发表评论

匿名网友

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

确定