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
Syntax
func append(s []T, elems ...T) []T
Parameters
| Parameter | Description |
|---|---|
s |
The slice to extend. |
elems |
Elements to add; use other... to append a whole slice. |
Return value
The updated slice.
Examples
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.
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.
Related
make· Create and initialise a slice, map or channel, optionally with a length and capacity (slices) or buffer size (channels).len and cap· len returns the number of elements in a string, slice, map, array or channel; cap returns a slice's or channel's capacity.- Go Arrays and Slices · tutorial