The append()
function in Go appends the specified elements to the end of a slice.
The append()
function accepts the following parameters:
The
append()
function returns the updated slice of the same type as the input slice.
The following code demonstrates how to use the append()
function in Golang:
package mainimport "fmt"func main(){// Example 1// create a slice of type intexample := []int{11,22,33,44}// display slicefmt.Println(example)// append 55example = append(example, 55)//display slicefmt.Println(example)// Example 2// append 66 and 77example = append(example, 66, 77)//display slicefmt.Println(example)// Example 3anotherSlice := []int{88,99,111}example = append(example, anotherSlice...)fmt.Println(example)}
The program creates a slice of type int
that contains 11, 22, 33, 44.
Example 1 uses the append()
function to add a single number, 55, at the end of the slice.
Example 2 appends multiple numbers, 66 and 77, at the end of the slice.
Example 3 creates another slice of type int
that contains 88, 99, 111, and then appends it at the end of the slice through the same method as the other examples.
It is important to add
...
at the end of the slice name to be appended so that the program knows to append all the slice elements.
Free Resources