Slices

Contents

Slices#

A slice is a header (pointer + length + capacity) backed by an array. The most-used composite in Go.

Slice literal.

xs := []int{1, 2, 3}

Append may reallocate the backing array.

xs = append(xs, 4)
fmt.Println(len(xs), cap(xs))

Pre-sized slice with make.

ys := make([]int, 5)         // length 5, cap 5

Pre-allocated with a cap hint to avoid re-allocations.

zs := make([]int, 0, 16)     // length 0, cap 16

Sub-slice shares the backing array; mutations on either are visible through both.

sub := xs[1:3]               // [2 3]; shares backing array

Copy when isolation matters.

isolated := make([]int, len(sub))
copy(isolated, sub)

References#