Sobes.tech
Senior

What is a slice? What is under the hood of a slice? How does the append function work?

sobes.tech AI

Answer from AI

A slice in Go is a dynamic array that is a structure with three fields:

  • Pointer to the array (underlying array in memory)
  • Length (len) — the number of elements accessible in the slice
  • Capacity (cap) — the maximum number of elements the underlying array can hold starting from the pointer

Under the hood, a slice is a small structure, roughly like this:

type sliceHeader struct {
    Data uintptr // pointer to the first element of the array
    Len  int
    Cap  int
}

The append function adds elements to the slice. If the length of the slice is less than its capacity, append simply writes new elements into the underlying array and increases the length. If the length reaches the capacity, append allocates a new array with increased capacity (usually twice as large), copies the old elements there, adds new elements, and returns a new slice with an updated pointer.

Example:

s := []int{1, 2, 3}
s = append(s, 4) // if cap(s) > len(s), it just adds 4

// if cap(s) == len(s), it allocates a new array, copies [1,2,3], adds 4

Thus, append can return a new slice, and it is important to assign the result back.

What is a slice? What is under the hood of a slice… - sobes.tech