Quidest?

Go slices length and capacity

· Lorenzo Drumond

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.

The length and capacity of a slice s can be obtained using the expressions len(s) and cap(s)

You can extend a slice’s length by re-slicing it, provided it has sufficient capacity. If you try to extend it beyond its capacity, it will panic

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6	s := []int{2, 3, 5, 7, 11, 13}
 7	printSlice(s)
 8
 9	// Slice the slice to give it zero length.
10	s = s[:0]
11	printSlice(s)
12
13	// Extend its length.
14	s = s[:4]
15	printSlice(s)
16
17	// Drop its first two values.
18	s = s[2:]
19	printSlice(s)
20
21	s = s[:]
22	printSlice(s)
23}
24
25func printSlice(s []int) {
26	fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
27}
28
29// Output:
30// len=6 cap=6 [2 3 5 7 11 13]
31// len=0 cap=6 []
32// len=4 cap=6 [2 3 5 7]
33// len=2 cap=4 [5 7]
34// len=2 cap=4 [5 7]

References

Next -> slice-zero-value

Next -> creating-a-slice-with-make

#slice #structured #capacity #length #array #data #golang #type