Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 329
Lance Avatar asked Dec 08 '22 04:12

Lance


1 Answers

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

like image 55
Stephen Weinberg Avatar answered Dec 11 '22 08:12

Stephen Weinberg