In Go, we can append new elements to a slice and remove elements from the slice using a built-in append()
function.
func append(slice []T, values ...T) []T
T
: This is a slice with the arbitrary values of the type T
to append.T
The resulting value of the append is a slice containing all the elements of the original slice plus the provided values.
Let’s look at a simple example of append()
in action.
package mainimport "fmt"func main() {slice := []int{1, 2, 3, 4, 5};fmt.Print("Slice before append: ");fmt.Println(slice)slice = append(slice, 10);fmt.Print("Slice after append: ");fmt.Println(slice)}
That was quite simple. The value got inserted at the end of the slice. But how do we add an element to the beginning of the slice or at a specific index in the slice?
The beauty of Go is that it forces a programmer to think like a programmer. In other languages, there're different functions for inserting at the start, at the end, and at the specific index. But, in Go we can use the same append function to do all of that.
package mainimport "fmt"func main() {slice := []int{1, 2, 3, 4, 5};fmt.Print("Slice before append: ");fmt.Println(slice)slice = append([]int{10}, slice...);fmt.Print("Slice after append: ");fmt.Println(slice)}
int
to []int
.Notice, the ...
at the end of the slice. The second parameter of the append
is a variadic parameter. A variadic parameter accepts zero or more values of a specified type.
From the Go Spec: If
f
is variadic with final parameter type...T
, then within the function the argument is equivalent to a parameter of type[]T
. At each call off
, the argument passed to the final parameter is a new slice of type[]T
whose successive elements are the actual arguments, which all must be assignable to the typeT
.
package mainimport ("fmt""math/rand""time")func main() {slice := []int{1, 2, 3, 4, 5};fmt.Print("Slice before append: ");fmt.Println(slice)rand.Seed(time.Now().UnixNano())idx := rand.Intn(len(slice))fmt.Println("Index:", idx)tempSlice := append(slice[:idx], 10)slice = append(tempSlice, slice[idx + 1:]...)fmt.Print("Slice after append: ");fmt.Println(slice)}
To append an element at a specific index we have to use slicing.
idx
and added the new element to the end of it.tempSlice
and appending the remaining slice at the end of it.This solution works even if we want to insert at the start or end. These scenarios cover all that is to appending a new element to a slice. Imagine if we can even remove/delete an element using the same append
function?
Here's an example:
package mainimport "fmt"func main() {slice := []int{1, 2, 3, 4, 5};fmt.Print("Slice before append: ");fmt.Println(slice)slice = append(slice[: len(slice)-1]);fmt.Print("Slice after append: ");fmt.Println(slice)}
We can also delete from the start or a specific index using the techniques discussed above.