Junior — Middle
Can you explain how a dynamic array is implemented and works in Go?
sobes.tech AI
Answer from AI
In Go language, a dynamic array is implemented through the slice type — a structure that contains a pointer to an array, a length, and a capacity.
When a slice is created, it points to a fixed-size underlying array. If, when adding elements, the length of the slice reaches its capacity, a new array with increased capacity (usually twice as large) is created, and the data is copied into it. This allows efficient memory management and dynamic array expansion.
Example:
var s []int // empty slice
s = append(s, 1) // add an element
s = append(s, 2, 3) // add multiple elements
fmt.Println(s) // [1 2 3]
Here, append automatically expands the underlying array when necessary, hiding memory management details from the developer.