Sobes.tech
Senior

Tell about slices in Go, their structure and internal headers.

sobes.tech AI

Answer from AI

In Go, a slice is a dynamic, resizable, sequential data type that represents a window on an array. A slice does not contain the data itself, but only describes a part of the array.

Internally, a slice is structured as a structure with three fields:

  • Pointer — a pointer to the first element of the array, corresponding to the start of the slice.
  • Length (len) — the current length of the slice, i.e., the number of elements available for reading.
  • Capacity (cap) — the maximum number of elements that can be held, starting from the pointer, without allocating new memory.

An example of the internal representation of a slice:

// Simplified representation
type SliceHeader struct {
    Data uintptr // pointer to the array
    Len  int     // length of the slice
    Cap  int     // capacity of the slice
}

When you create a slice, it references an array, and operations on the slice (such as adding elements via append) may lead to the allocation of a new array if the capacity is exceeded.

Thus, a slice is a convenient and efficient way to work with sequences, allowing dynamic resizing without copying data when expanding, as long as the capacity is not exceeded.