How to use the append function

yourbasic.org/golang

Basics

The built-in append function is appends any number of elements to the end of a slice:

Append returns the updated slice. Therefore you need to store the result of an append, often in the variable holding the slice itself:

a := []int{1, 2}
a = append(a, 3, 4) // a == [1 2 3 4]
Warning: See Why doesn’t append work every time? for an example of what can happen if your forget that append may reuse the underlying array.

Slice to slice

You can concatenate two slices using the three dots notation:

a := []int{1, 2}
b := []int{11, 22}
a = append(a, b...) // a == [1 2 11 22]

The result does not depend on whether the arguments overlap:

a := []int{1, 2}
a = append(a, a...) // a == [1 2 1 2]

String to byte slice

As a special case, it’s legal to append a string to a byte slice:

slice := append([]byte("Hello "), "world!"...)

Time complexity

Appending a single element takes constant amortized time. See Amortized time complexity for a detailed explanation.

Further reading

Slices in a nutshell

Share this page: