~/Go Rambling
Oct 12, 2024
In Go, slices are, as the name implies, slices of arrays.
A slice is composed of a pointer to an underlying array,
a length, and a capacity. The syntax to take a slice is
arr[start:end]
, where start
is inclusive, and end
is exclusive.
Omitting start
defaults to 0
, and omitting end
uses the slice/array’s length.
Model of a Slice
graph TD; subgraph Backing Array A[Backing Array]; Length E[Capacity]; end subgraph Slice B[Slice] D[Length]; CAP[Capacity]; end A --> Length B[Slice] -.- |reference|A[Backing Array] B --> D[Length]; A --> E[Capacity]; B --> CAP[Capacity]; CAP -.-> |equal or less than|E;
slice expression examples
|
|
y := x[:]
creates a shallow copy of the slice x in Go, both x and y share the same
backing array.
A backing array of a slice can potentially occupy a larger memory chunk than is needed leading to waste.
The simplest way to fix this is to create a new slice with its own backing array.
References