Tell me about working with slices in Golang: how do capacity, length work, and what happens when going out of bounds
sobes.tech AI
Answer from AI
In Go, a slice is a structure that contains a pointer to an array, a length, and a capacity.
- length — the number of elements available for reading and writing through the slice.
- capacity — the maximum number of elements the slice can hold, starting from the current pointer.
When creating a slice, for example:
s := make([]int, 3, 5)
length will be 3, capacity — 5.
If you access an element with an index exceeding length, for example s[3], a panic will occur: runtime error: index out of range.
However, you can extend the slice using slicing operation if the index does not exceed capacity:
s = s[:5] // now length = 5
If adding elements causes length to exceed capacity, Go will create a new array with increased capacity, copy the data, and return a new slice.
Thus, length is the current length of the slice, and capacity is the maximum length without allocating new memory. Going beyond length causes an error, and exceeding capacity is impossible without reallocation.