How to add an element to a slice in Golang

What are slices?

Slices are a built-in data type in Golang similar to arrays, except that a slice has no specified length. All elements within a slice must have the same type.

The code below shows how to declare a slice literal with the string type specification.

newSlice := []string{"a", "b", "c", "d"}

How to add an element to a slice

To add an element to a slice, you can use Golang’s built-in append method. append adds elements from the end of the slice.

The syntax of the append method is shown below:

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

The first parameter to the append method is a slice of type T. Any additional parameters are taken as the values to add to the given slice.

Note: The values to add to the slice must be of the same type specification as the slice itself.

The append method returns a slice that contains all the original values in addition to the newly added values. If the backing array of the given slice is too small to handle the addition of the new elements, the append method allocates a bigger array to which the returned slice points.

You can read more about the append method here.

Code

The code below shows how to add elements to a slice.

package main
import (
"fmt"
)
func main(){
// initialize a slice literal
newSlice := []string{"a", "b", "c", "d"}
fmt.Println("The original slice is:", newSlice)
// add an element to the slice
newSlice = append(newSlice, "e")
fmt.Println("The updated slice is:", newSlice)
// add multiple values to the slice
newSlice = append(newSlice, "f", "g", "h")
fmt.Println("The final slice is:", newSlice)
}

Explanation

In the code above:

  • In line 4: We import the fmt package for printing.

  • In line 10: We initialize a slice literal of the string type called newSlice. At the time of declaration, newSlice contains 44 values.

  • In line 14: We use the append method and then add the element e to newSlice.

  • In line 18: We use the append method to add the elements f, g, and h to newSlice. The output is the final slice after all additions.

Free Resources