Junior — Middle
How are sizes and reserve volumes of slices stored in programming language memory?
sobes.tech AI
Answer from AI
In Go, a slice is a data structure that contains three main fields:
- Pointer to array — address of the first element of the slice in memory.
- Length (len) — the number of elements available for reading.
- Capacity (cap) — the maximum number of elements the slice can hold without allocating new memory.
In memory, a slice is roughly represented as:
type SliceHeader struct {
Data uintptr // pointer to array
Len int // length of the slice
Cap int // capacity of the slice
}
When creating a slice, an array with a certain capacity is allocated. If adding elements exceeds the capacity, a new larger array is allocated, and data is copied there.
The reserve volume (capacity) allows efficient memory management, reducing allocations during growth.
Example:
s := make([]int, 3, 5) // len=3, cap=5
s = append(s, 4) // len=4, cap=5
s = append(s, 5) // len=5, cap=5
s = append(s, 6) // len=6, cap=10 (new memory allocated)
Thus, slice sizes and capacities are stored in the slice structure and managed automatically during runtime.