Junior — Middle
Could you explain how a dynamic array (slice) is implemented in a programming language?
sobes.tech AI
Answer from AI
In Go language, a slice is a dynamic array that is a structure with three main fields:
- Pointer to array: the slice contains a reference to the underlying array where data is stored.
- Length (len): the number of elements available for reading and writing.
- Capacity (cap): the maximum number of elements the underlying array can hold without allocating new memory.
When a slice reaches its capacity and a new element needs to be added, a new larger array is allocated, existing data is copied, and the slice pointer is updated.
Example:
s := make([]int, 0, 3) // length 0, capacity 3
s = append(s, 1, 2, 3) // now length 3
s = append(s, 4) // capacity exceeded, a new array is allocated
Thus, slices provide convenience for working with dynamic arrays, hiding memory management details.