Sobes.tech
Senior

How is Slice organized under the hood in Go?

sobes.tech AI

Answer from AI

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

  1. Pointer to array — the address of the first element of the slice in the underlying array.
  2. Length — the number of elements accessible through the slice.
  3. Capacity — the maximum number of elements that can be stored starting from the pointer without allocating new memory.

Under the hood, a slice is simply a small structure that references a part of an array. When expanding a slice (append), if the capacity is exceeded, a new larger array is created, and data is copied there.

An example of a slice structure in Go (simplified):

// sliceHeader — internal representation of a slice
type sliceHeader struct {
    ptr *ElementType // pointer to the first element
    len int          // length of the slice
    cap int          // capacity of the slice
}

Thus, slices are lightweight structures that allow working with dynamic arrays without copying data when passing by value.

How is Slice organized under the hood in Go? — C# - sobes.tech