To append elements to a slice in Go, you can use the built-in append()
function. The append()
function takes the slice and the elements you want to append as arguments, and returns a new slice with the appended elements.
Here's an example:
package main
import "fmt"
func main() {
// Create a slice
numbers := []int{1, 2, 3, 4, 5}
// Append elements to the slice
numbers = append(numbers, 6, 7, 8)
// Print the updated slice
fmt.Println(numbers) // Output: [1 2 3 4 5 6 7 8]
}
In the example above, the numbers
slice is initially created with some elements. Then, the append()
function is used to append the numbers 6
, 7
, and 8
to the slice. Finally, the updated numbers
slice is printed which includes the appended elements.
Note that append()
function not only appends individual elements, but it can also be used to append another slice to an existing slice. For example:
package main
import "fmt"
func main() {
// Create two slices
numbers1 := []int{1, 2, 3}
numbers2 := []int{4, 5, 6}
// Append numbers2 slice to numbers1 slice
numbers1 = append(numbers1, numbers2...)
// Print the updated slice
fmt.Println(numbers1) // Output: [1 2 3 4 5 6]
}
In this example, the append()
function is used to append the numbers2
slice to the numbers1
slice using the ellipsis (...
) operator after numbers2
. The ellipsis allows the second slice to be expanded into individual elements, which can be appended to the first slice.