Home »
Golang
Go Append Elements To a Slice
Last Updated : May 05, 2025
In Go, you can add elements to a slice using the built-in append()
function. This is useful when you want to expand a slice by including more items dynamically.
Syntax
The syntax for appending elements to a slice is:
slice = append(slice, element)
You can also append multiple elements at once:
slice = append(slice, elem1, elem2, elem3)
Appending Single Element
Use the append()
function to add a single element to an existing slice.
Example
In this example, we are appending one new element to a slice:
package main
import "fmt"
func main() {
colors := []string{"Red", "Green"}
colors = append(colors, "Blue") // Append one element
fmt.Println("Colors slice after append:", colors)
}
When executed, this program outputs:
Colors slice after append: [Red Green Blue]
Appending Multiple Elements
You can add more than one element at a time by listing them all in the append()
function.
Example
In this example, we append two new elements to the slice:
package main
import "fmt"
func main() {
languages := []string{"Go", "Python"}
languages = append(languages, "Java", "C++") // Append multiple elements
fmt.Println("Updated languages slice:", languages)
}
When executed, this program outputs:
Updated languages slice: [Go Python Java C++]
Appending Another Slice
You can also append all elements from one slice to another using the ...
(variadic) operator.
Example
In this example, we append all elements from one slice to another:
package main
import "fmt"
func main() {
slice1 := []int{1, 2}
slice2 := []int{3, 4, 5}
slice1 = append(slice1, slice2...) // Append another slice
fmt.Println("Combined slice:", slice1)
}
When executed, this program outputs:
Combined slice: [1 2 3 4 5]
Appending in a Loop
You can use a for
loop to dynamically build a slice by appending elements during each iteration.
Example
In this example, we create an empty slice and append numbers using a loop:
package main
import "fmt"
func main() {
var nums []int
for i := 1; i <= 3; i++ {
nums = append(nums, i)
}
fmt.Println("Final slice:", nums)
}
When executed, this program outputs:
Final slice: [1 2 3]
Exercise
Select the correct option to complete each statement about appending elements to a slice in Go.
- To append an element x to a slice s, the syntax is ___.
- Appending an element to a slice might create a new underlying array if the slice ___.
- To append all elements from slice b to slice a, the correct syntax is ___.
Advertisement
Advertisement