Middle+
What is a slice in Go? How do len and cap differ?
sobes.tech AI
Answer from AI
A slice in Go is a dynamic, resizable view of a sequence of elements of the same type, based on an array. A slice contains a pointer to the underlying array, a length (len), and a capacity (cap).
- len(slice) — the number of elements accessible in the slice, i.e., the length of the slice.
- cap(slice) — the maximum number of elements the slice can hold without allocating new memory, i.e., the size of the underlying array from the start of the slice.
Example:
arr := [5]int{1, 2, 3, 4, 5}
s := arr[1:3] // a slice of elements with indices 1 and 2
fmt.Println(len(s)) // 2
fmt.Println(cap(s)) // 4 (from index 1 to the end of the array)
Thus, len determines the current length of the slice, and cap indicates how many elements can be added without reallocating memory.