The append function is a built-in feature in Go that allows you to add elements to the end of a slice. It’s essential for dynamic array-like operations in Go, where slices are the primary way to handle collections of data. This guide explains how append works, including appending individual elements and entire slices.
The Append Function Signature
The signature of append is:
func append(slice []T, elements ...T) []T
Here, T is a placeholder for any type. The function takes a slice and a variadic parameter of elements to append, returning a new slice with the added elements.
Appending Individual Elements
You can append multiple elements to a slice easily:
x := []int{1, 2, 3}
x = append(x, 4, 5, 6)
fmt.Println(x) // Output: [1 2 3 4 5 6]
The append function modifies the slice and returns the updated version, which you must assign back to the variable.
Appending a Slice to a Slice
To append one slice to another, use the ... operator to expand the slice into individual elements:
x := []int{1, 2, 3}
y := []int{4, 5, 6}
x = append(x, y...)
fmt.Println(x) // Output: [1 2 3 4 5 6]
Without ..., the code won’t compile because y is a slice, not an int.
How Append Works Internally
When appending, Go checks if the underlying array has enough capacity. If not, it allocates a new array with increased capacity (usually doubling the size), copies the elements, and appends the new ones. This ensures efficient growth.
x := make([]int, 0, 3) // Length 0, capacity 3
x = append(x, 1, 2, 3)
fmt.Println(len(x), cap(x)) // Output: 3 3
x = append(x, 4) // Capacity exceeded, new array allocated
fmt.Println(len(x), cap(x)) // Output: 4 6 (or similar, depending on Go version)
Edge Cases and Best Practices
- Nil Slices: Appending to a nil slice works fine:
var x []int; x = append(x, 1). - Avoid Common Mistakes: Remember to assign the result back:
x = append(x, value). - Performance: Appending in a loop can cause multiple reallocations. Pre-allocate if possible:
x := make([]int, 0, expectedSize). - Variadic Nature: The
...operator is key for appending slices or multiple values.
Conclusion
The append function is powerful and flexible, enabling dynamic slice manipulation in Go. Understanding its behavior helps write efficient code. For more details, refer to the official documentation.