0
0
Goprogramming~5 mins

Appending to slices in Go

Choose your learning style9 modes available
Introduction
Appending to slices lets you add new items to a list that can grow as needed.
When you want to add a new item to a list of names.
When collecting user inputs one by one into a list.
When building a list of results from a loop.
When you don't know the final size of the list in advance.
Syntax
Go
slice = append(slice, newElement)
The append function returns a new slice with the element added.
You must assign the result back to the slice variable to keep the change.
Examples
Adds the number 4 to the end of the numbers slice.
Go
numbers := []int{1, 2, 3}
numbers = append(numbers, 4)
Adds the word "fun" to the words slice.
Go
words := []string{"go", "is"}
words = append(words, "fun")
Starts with an empty slice and adds 10 as the first element.
Go
var empty []int
empty = append(empty, 10)
Sample Program
This program creates a slice of fruits, adds "cherry" to it, and prints the updated slice.
Go
package main

import "fmt"

func main() {
    fruits := []string{"apple", "banana"}
    fruits = append(fruits, "cherry")
    fmt.Println(fruits)
}
OutputSuccess
Important Notes
Appending may create a new underlying array if the current one is full.
Always assign the result of append back to the slice variable.
You can append multiple elements at once: append(slice, elem1, elem2).
Summary
Use append to add elements to slices easily.
Remember to assign the result of append back to your slice.
Appending grows the slice dynamically as needed.