Junior — Middle
Kas saaksite selgitada, kuidas on realiseeritud dünaamilise massiivi (slice) struktuur programmeerimiskeeles?
sobes.tech AI
Vastus AI-lt
In the Go language, a slice is a dynamic array that represents a structure with three main fields:
- Pointer to the 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, new array allocated
Thus, slices facilitate working with dynamic arrays, hiding the details of memory management.