VOOZH about

URL: https://www.geeksforgeeks.org/go-language/how-to-append-a-slice-in-golang/

⇱ How to append a slice in Golang? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to append a slice in Golang?

Last Updated : 12 Jul, 2025

In Go, slices are dynamically-sized, flexible views into the elements of an array. Appending elements to a slice is a common operation that allows for the expansion of the slice as needed. The built-in append function is used to add elements to the end of a slice.In this article,we will learn How to Append a Slice in Golang.

Example

 package main 
import "fmt"

func main() {
// Initial slice
numbers := []int{1, 2, 3}
fmt.Println("Original slice:", numbers)

// Appending elements
numbers = append(numbers, 4, 5, 6)
fmt.Println("After appending:", numbers)
}

Syntax of append

The append function has the following syntax:

slice = append(slice, elements...)

Where:

  • slice is the original slice to which elements are being added.
  • elements are the values being appended. The ... operator is used to append multiple elements.

Appending Multiple Elements

You can append multiple elements to a slice at once using the append function.

Example


Output
Original slice: [a b]
After appending: [a b c d]

Appending Another Slice

You are allowed to append one slice to another with the help of the ... operator. This allows for a seamless combination of slices.

Example


Output
S1: [1 2 3]
S2: [4 5 6]
After appending S2 to S1: [1 2 3 4 5 6]

Understanding Capacity and Growth

When appending to a slice, if the length of the slice exceeds its capacity, Go automatically allocates a new underlying array to accommodate the additional elements.

Example


Output
Initial slice capacity: 3
After initial append, capacity: 3
After exceeding capacity, capacity: 6



Comment
Article Tags:

Explore