Go: Append function explained

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

slice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)

Appending a single element takes constant amortized time. The article Amortized time complexity explains this in detail.

Special case

It is legal to append a string to a byte slice:

slice = append([]byte("hello "), "world"...)


Example: Append an element to a slice:

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

Example: Concatenate two slices:

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

Example: The result does not depend on whether the arguments overlap, so we can for instance concatenate a slice with itself:

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


Be the first to comment!