Sobes.tech
Senior

What fields does a slice in Go consist of?

sobes.tech AI

Answer from AI

A slice in Go consists of three fields:

  1. Pointer to array — the address of the first element of the slice in the underlying array.
  2. Length (len) — the number of elements available in the slice.
  3. Capacity (cap) — the maximum number of elements the slice can hold, starting from the current pointer.

These fields allow the slice to be a dynamic view of a part of an array with the ability to expand when necessary.

An example of a slice structure (simplified):

type SliceHeader struct {
    Data uintptr // pointer to the array
    Len  int     // length of the slice
    Cap  int     // capacity of the slice
}
What fields does a slice in Go consist of? — Golang - sobes.tech