Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cap vs len of slice in golang

Tags:

slice

go

What is the difference between cap and len of a slice in golang?

According to definition:

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 

Does the len mean non null values only?

like image 288
Ali Adravi Avatar asked Jan 16 '17 00:01

Ali Adravi


People also ask

What is the difference between Len () and cap () functions of slice in Go?

cap tells you the capacity of the underlying array. len tells you how many items are in the array. 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.

What is Golang cap function?

The Cap function of the reflect module in Golang returns the capacity of a provided parameter, depending on the parameter's type.

How do you find the size of a slice in Golang?

To get length of slice in Go programming, call len() function and pass the slice as argument to it. len() function returns an integer, the length of slice.

What is the maximum capacity of slice in Golang?

The length of the slice is 5, which means the total number of elements present in the slice is 5 and the capacity of the slice 6 means it can store a maximum of 6 elements in it.


1 Answers

A slice is an abstraction that uses an array under the covers.

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

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.

Example:

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) } 

Will output something like this:

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 

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.

Play example

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.

like image 84
jmaloney Avatar answered Oct 04 '22 15:10

jmaloney