Go 1.27 reference · Built-in Functions

Go append Function

Add elements to the end of a slice, growing its backing array when needed; always assign the result back.

Go 1.27

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

func append(s []T, elems ...T) []T

Parameters

ParameterDescription
s The slice to extend.
elems Elements to add; use other... to append a whole slice.

Return value

The updated slice.

Examples

Example 1
package main

import "fmt"

func main() {
	items := []string{"mug"}
	items = append(items, "teapot", "kettle")
	more := []string{"cup", "saucer"}
	items = append(items, more...)
	fmt.Println(items, len(items))
}

Output

[mug teapot kettle cup saucer] 5

Run this on your computer — see “Get Started” for setup.

Shared backing arrays
package main

import "fmt"

func main() {
	a := make([]int, 3, 4)
	b := append(a, 1) // fits in capacity: shares a's array
	c := append(a, 2) // overwrites the same slot!
	fmt.Println(b, c)
	d := append(a[:3:3], 9) // full slice expression forces a copy
	fmt.Println(d, a)
}

Output

[0 0 0 2] [0 0 0 2]
[0 0 0 9] [0 0 0]

Run this on your computer — see “Get Started” for setup.

When capacity is exceeded, append allocates a new array (roughly doubling small slices). Two slices appended from the same base can share memory; use a full slice expression s[:len:len] or slices.Clone to avoid surprises.

Was this page helpful?