Senior
How is a slice organized under the hood in Go?
sobes.tech AI
Answer from AI
In Go, a slice is a structure that contains three main fields:
- pointer to array — the address of the first element of the slice in the underlying array;
- length (len) — the number of elements accessible in the slice;
- capacity (cap) — the maximum number of elements that can be stored in the underlying array starting from the pointer.
Under the hood, a slice is not an array but a "window" into a part of an array. When adding elements using append, if the length exceeds the capacity, a new larger array is created, and data is copied there.
Example of a slice structure (simplified):
type sliceHeader struct {
ptr *ElementType
len int
cap int
}
This allows efficient work with dynamic arrays without copying data on each addition, as long as the current capacity is not exceeded.