Andrew's Digital Garden

Slices in Go

Slices in Go are similar to arrays. [[20200720115114-go-arrays]]

Given an array a:

a := [8]int{}

The slice operation creates a slice from array a, from element 3 up to, but not including, element 7.

s := a[3:7]

This slice acts as a reference to the underlying array, so modifying a slice will affect the underlying array (and also any other slices of said array).

append lets you append new elements to a slice (returns a new slice), while simultaneously increasing the capacity of the slice if necessary. This expansion may be done by creating a new underlying array.

Slices can be created from scratch without an array - an underlying array is still being created but will remain anonymous:

var s []int // s == nil s = []int{} // s == []

length of a slice refers to the amount of elements inside the slice len() capacity of a slice refers to the amout of elements in the underlying array cap()

[[go]]

Referred in

Slices in Go