How to use the append function in Go

The append() function in Go appends the specified elements to the end of a slice.

Prototype

Parameters and return value

The append() function accepts the following parameters:

  • A slice of any valid Golang type.
  • Elements to append after the given slice that are of the same type as the slice.

The append() function returns the updated slice of the same type as the input slice.

Example

The following code demonstrates how to use the append() function in Golang:

package main
import "fmt"
func main(){
// Example 1
// create a slice of type int
example := []int{11,22,33,44}
// display slice
fmt.Println(example)
// append 55
example = append(example, 55)
//display slice
fmt.Println(example)
// Example 2
// append 66 and 77
example = append(example, 66, 77)
//display slice
fmt.Println(example)
// Example 3
anotherSlice := []int{88,99,111}
example = append(example, anotherSlice...)
fmt.Println(example)
}

Explanation

The program creates a slice of type int that contains 11, 22, 33, 44.

Example 1

Example 1 uses the append() function to add a single number, 55, at the end of the slice.

Example 2

Example 2 appends multiple numbers, 66 and 77, at the end of the slice.

Example 3

Example 3 creates another slice of type int that contains 88, 99, 111, and then appends it at the end of the slice through the same method as the other examples.

It is important to add ... at the end of the slice name to be appended so that the program knows to append all the slice elements.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved