Append

The append function is the primary way to grow a slice.

Usage

append takes a slice and one or more elements to add. It returns a new slice (which may point to a new underlying array if the capacity was exceeded).

slice := []int{1, 2}
slice = append(slice, 3)
slice = append(slice, 4, 5)

Appending a Slice

You can append one slice to another using the spread operator.

s1 := []int{1, 2}
s2 := []int{3, 4}
s1 = append(s1, s2...)

Memory & Performance

If the capacity of the original slice isn’t large enough, append will allocate a new, larger array and copy the old elements over. This is why you should always assign the result of append back to the original slice variable.