How to Append a Slice in Golang

To append a slice in Golang, you can use the “append()” function.

The append() function appends any number of elements to the end of a slice and returns the updated slice. It doesn’t modify the original slice but creates a new slice, copies all the elements from the original slice, and puts the provided elements at the end.

Syntax

func append(slice []Type, elems ...Type) []Type

Parameters

The append() is a variadic function(function with a variable number of arguments) that takes the following arguments

  1. slice: The slice to be appended.
  2. elems: One or more(variable) elements of the same type as the slice.

Return value

The return value is the final slice containing all the elements appended at the end of the original slice.

Note: The append() copies the elements and creates a new slice. The original slice is not modified.

Example

package main

import "fmt"

func main() {
  s := []int{} // empty slice

  s = append(s, 1) // appending 1 element to empty slice => s = [1]
  fmt.Println(s)

  s = append(s, 2) // appending 1 element to non-empty slice => s = [1, 2]
  fmt.Println(s)

  s = append(s, 3, 4) // appending multiple elements => s = [1, 2, 3, 4]
  fmt.Println(s)
}

Output

[1]
[1 2]
[1 2 3 4]

First, we defined an empty slice, then appended elements one by one, and the final output was a slice with four elements.