Sobes.tech
Middle+

What does a slice consist of, its internal structure?

sobes.tech AI

Answer from AI

A slice in Go is a structure that contains three main fields:

  1. Pointer to an array — the address of the first element of the slice within the underlying array.
  2. Length (len) — the number of elements available in the slice.
  3. Capacity (cap) — the maximum number of elements that can be held, starting from the pointer, without allocating new memory.

Internally, a slice is not an array but just a "window" into a part of an array. When the slice is modified (for example, by adding elements through append), if the length exceeds the capacity, a new array is created, and data is copied there.

An example of a slice structure (simplified):

Type SliceHeader struct {
    Data uintptr // pointer to the first element of the array
    Len  int     // length of the slice
    Cap  int     // capacity of the slice
}

This allows efficient work with dynamic sequences without copying data when slicing.