Appending to a slice

It is common to append new elements to a slice, and so Go provides a built-in append function. The documentation of the built-in package describes append.

  1. func append(s []T, vs ...T) []T

The first parameter s of append is a slice of type T, and the rest are T values to append to the slice.

The resulting value of append is a slice containing all the elements of the original slice plus the provided values.

If the backing array of s is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.

(To learn more about slices, read the Slices: usage and internals article.)

append.go

  1. package main
  2. import "fmt"
  3. func main() {
  4. var s []int
  5. printSlice(s)
  6. // append works on nil slices.
  7. s = append(s, 0)
  8. printSlice(s)
  9. // The slice grows as needed.
  10. s = append(s, 1)
  11. printSlice(s)
  12. // We can add more than one element at a time.
  13. s = append(s, 2, 3, 4)
  14. printSlice(s)
  15. }
  16. func printSlice(s []int) {
  17. fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
  18. }