How to Append to Slice in Go: Simple Syntax and Examples
In Go, you append to a slice using the built-in
append function like this: slice = append(slice, element). This adds the element to the end of the slice and returns the updated slice.Syntax
The basic syntax to append an element to a slice is:
slice = append(slice, element)Here:
sliceis your existing slice variable.elementis the value you want to add.- The
appendfunction returns a new slice with the element added. - You must assign the result back to the slice variable because the underlying array may change.
go
slice = append(slice, element)Example
This example shows how to create a slice of integers and append new numbers to it:
go
package main import "fmt" func main() { numbers := []int{1, 2, 3} fmt.Println("Before append:", numbers) numbers = append(numbers, 4) numbers = append(numbers, 5, 6) fmt.Println("After append:", numbers) }
Output
Before append: [1 2 3]
After append: [1 2 3 4 5 6]
Common Pitfalls
One common mistake is forgetting to assign the result of append back to the slice variable. Since append may create a new underlying array, the original slice won't change if you don't assign it.
Wrong way:
slice := []int{1, 2}
append(slice, 3) // result ignored, slice unchanged
fmt.Println(slice) // prints [1 2]Right way:
slice := []int{1, 2}
slice = append(slice, 3) // assign back
fmt.Println(slice) // prints [1 2 3]Quick Reference
- append(slice, element): Add one element.
- append(slice, elem1, elem2, ...): Add multiple elements.
- append(slice1, slice2...): Add all elements from another slice.
- Always assign the result back to your slice variable.
Key Takeaways
Use the built-in append function to add elements to a slice in Go.
Always assign the result of append back to your slice variable.
You can append single or multiple elements at once.
Appending may create a new underlying array, so assignment is necessary.
Appending slices requires the ... operator to unpack elements.