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:
sliceis the original slice to which elements are being added.elementsare 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
package main
import "fmt"
func main() {
// Initial slice
letters := []string{"a", "b"}
fmt.Println("Original slice:", letters)
// Appending multiple elements
letters = append(letters, "c", "d")
fmt.Println("After appending:", letters)
}
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
package main
import "fmt"
func main() {
// Initial slices
s1 := []int{1, 2, 3}
s2 := []int{4, 5, 6}
fmt.Println("S1:", s1)
fmt.Println("S2:", s2)
// Appending slice2 to slice1
s1 = append(s1, s2...) // Note the ... operator
fmt.Println("After appending S2 to S1:", s1)
}
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
package main
import "fmt"
func main() {
// Initial slice
numbers := make([]int, 0, 3) // Length: 0, Capacity: 3
fmt.Println("Initial slice capacity:", cap(numbers))
// Appending elements
numbers = append(numbers, 1, 2, 3)
fmt.Println("After initial append, capacity:", cap(numbers))
// Appending more elements
numbers = append(numbers, 4, 5)
fmt.Println("After exceeding capacity, capacity:", cap(numbers))
}
Output
Initial slice capacity: 3 After initial append, capacity: 3 After exceeding capacity, capacity: 6