How to append anything (element, slice or string) to a slice

yourbasic.org/golang

Basics

The built-in append function 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.

Concatenate 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 ... unpacks b. Without the dots, the code would attempt to append the slice as a whole, which is invalid.

The result does not depend on whether the arguments overlap:

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

Concatenate string to byte slice

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

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

Efficiency

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

Further reading

Slices and arrays in a nutshell

Share this page: