![]() |
VOOZH | about |
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.
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)
}
appendThe 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.You can append multiple elements to a slice at once using the append function.
Original slice: [a b] After appending: [a b c d]
You are allowed to append one slice to another with the help of the ... operator. This allows for a seamless combination of slices.
S1: [1 2 3] S2: [4 5 6] After appending S2 to S1: [1 2 3 4 5 6]
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.
Initial slice capacity: 3 After initial append, capacity: 3 After exceeding capacity, capacity: 6