Sobes.tech
Middle+

How is a slice in Go structured internally? How does the append function work?

sobes.tech AI

Answer from AI

In Go, a slice is a structure that contains three fields:

  • a pointer to an array (a pointer to the first element of the slice or to the start of the allocated array);
  • length (len) — the number of elements available in the slice;
  • capacity (cap) — the maximum number of elements that can be stored in the array starting from the pointer.

Thus, a slice is not an array, but a "window" into a part of an array.

The append function adds elements to a slice. If the length of the slice is less than its capacity, append simply writes new elements into the existing array and increases the slice's length. If the length reaches the capacity, a new array with increased capacity (usually twice as large) is allocated, old data is copied, and new elements are added there. A new slice pointing to the new array is returned.

Example:

s := make([]int, 0, 3) // length 0, capacity 3
s = append(s, 1, 2)    // adding 2 elements, length 2, capacity 3
s = append(s, 3)       // length 3, capacity 3
s = append(s, 4)       // capacity exceeded, a new array with larger capacity is allocated

Thus, append provides dynamic slice expansion with memory management under the hood.

How is a slice in Go structured internally? How does… - sobes.tech