liveBook · Manning

Append

As explained in Go in Action, Second Edition

append is a Go built-in function that adds elements to a slice and returns a slice representing the resulting sequence.

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

How Go in Action, Second Edition covers it

How deep it goes
Explains the signature, nil-slice safety, capacity reuse, reallocation, copying, amortized growth, and returned slice headers.
Examples
Uses integer slices, nil string slices, variadic additions, capacity traces, and addOneToAll across function boundaries.
What it assumes
Assumes slices, length, capacity, and backing arrays; teaches nil-slice append and reallocation behavior through concrete examples.
What you can do after
Apply it via Go’s built-in function to grow slices, append multiple values, inspect capacity, and return updated slices from functions.
How it connects
Connects slices with make, capacity, backing arrays, slice headers, and arrays.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.