Go Slices

From NovaOrdis Knowledge Base
Revision as of 00:49, 19 August 2024 by Ovidiu (talk | contribs) (→‎Overview)
Jump to navigation Jump to search

External

Internal

Overview

A slice is a descriptor, or a header, for a contiguous segment of an underlying array, stored separately from the slice variable, and provides access to a numbered sequence of elements from that array. A slice type denotes the set of all slices of arrays of its element type. The slice was used to be referred to as a reference type, but not anymore, "reference type" terminology was removed from Go documentation.

A slice contains a pointer to the underlying array, a length and a capacity. More details available in the structure section. A slice, once initialized, is always associated with the underlaying array that holds its elements. The slice shares storage with its array, and other slices of the same array. A distinct slice that shares the underlying array with an original slice can be created by slicing the original slice with a slice expression.

Structure

Under the covers, a slice is a structure that contains:

  • a pointer to the first element of the slice, as stored in the underlying array.
  • an integer length of the slice.

Slices and Pass-by-Value

When the slice is passed as a function argument, the structure is copied on the function's stack, so both the function argument slice, and the

Declaration and Initialization

Initialization with make()

Initialization with a Composite Literal

Initialization by Slicing the Underlying Array

Operators

Slice Expressions

Slice Expressions

TODEPLETE

Go Slices TODPLETE