append grows a Go slice by accepting an existing slice and one or more values, then returning the resulting slice. It is safe to use with a nil slice, and the returned value should normally replace the original slice variable. section 4.2.4
When capacity remains, append extends the existing backing array without allocating. When capacity is exhausted, Go allocates a larger backing array, copies the old and new values, and returns a new slice header with extra capacity to reduce future copying. section 4.2.2 section 4.2.4
Use append idiomatically by:
- Assigning its result back to the slice variable. section 4.2.4
- Appending several values directly or expanding another slice with .... section 4.2.4
- Preallocating capacity with make when the expected growth is known. section 4.2.2
- Returning the updated slice from a function that appends, because the caller’s length and backing array may no longer match the function’s slice. section 4.2.5
Growing and returning a slice
intSlice := []int{10, 20, 30} intSlice = append(intSlice, 40, 50) func addOneToAll(s []int) []int { s = append(s, 0) for i := range s { s[i] += 1 } return s } slice := addOneToAll(intSlice) The first operation adds multiple values. The function returns its appended slice so the caller can observe the new length and values. section 4.2.4 section 4.2.5
Listing 4.32 The append function
func append(slice []Type, elems ...Type) []Type
Inspect the built-in signature showing that append accepts a slice and variadic elements and returns a slice. section 4.2.4
