Senior
What happens to a slice in Go if its capacity is 8 and we try to add a ninth element?
sobes.tech AI
Answer from AI
In Go, a slice is a structure that contains a pointer to an array, a length (len), and a capacity (capacity). Capacity is the maximum number of elements that the current array can hold.
If a slice has a capacity of 8, and we try to add a ninth element using append, the following happens:
- Go allocates a new array with increased capacity (usually twice the current, so about 16).
- It copies all existing elements to the new array.
- It adds the new element.
- It returns a new slice pointing to this new array with an updated length and capacity.
Thus, append automatically expands the slice when capacity is exceeded, ensuring dynamic resizing.
Example:
s := make([]int, 8, 8) // length and capacity 8
s = append(s, 9) // add the 9th element
fmt.Println(len(s)) // 9
fmt.Println(cap(s)) // >= 9, usually 16