Sobes.tech
Senior

What is a slice? How is it structured internally?

sobes.tech AI

Answer from AI

In Go, a slice is a dynamic array that is represented as a structure with three fields:

  • Pointer to array — the address of the first element of the slice in the underlying array.
  • Length (len) — the number of elements available for reading.
  • Capacity (cap) — the maximum number of elements that can be stored in the slice without allocating new memory.

Inside a slice, data is not stored directly; it only references an array in memory. When adding elements, if the length exceeds the capacity, a new larger array is created, and data is copied there.

Example of a slice structure in Go:

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

Using a slice:

s := []int{1, 2, 3} // slice with length 3 and capacity 3
s = append(s, 4)     // if capacity allows, adds an element without allocation

Thus, slices are convenient for working with dynamic arrays, providing flexibility and efficiency.

What is a slice? How is it structured internally… - sobes.tech