Junior
What are len and capacity in slices in Go?
sobes.tech AI
Answer from AI
In Go, a slice consists of three fields: a pointer to the underlying array, the length (len), and the capacity (cap).
- Length (len): The number of elements actually contained in the slice. This is the number of accessible elements.
- Capacity (cap): The number of elements from the start of the slice to the end of the underlying array. This is the maximum number of elements that can be added to the slice without reallocating (creating a new underlying array).
// Creating a slice
slice := make([]int, 5, 10)
// len(slice) will return 5
// cap(slice) will return 10
// s2 references the same underlying array
s2 := slice[2:5]
// len(s2) will return 3 (5 - 2)
// cap(s2) will return 8 (10 - 2)
When adding elements to a slice using the append function, if the current length of the slice reaches its capacity, Go creates a new underlying array with a larger capacity, copies the old elements into it, and updates the slice pointer.