How to prepend into a slice in Go
December 24, 2021

In Go there is no built-in function to prepend an element into a slice.
however there is a simple trick we can use to do a prepend operation easily using the built-in function append.

slice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)

As you can see in the second form, anotherSlice is appended to slice .
Now if we change the order of these parameters:

slice = append(anotherSlice, slice...)

Now anotherSlice is prepended to slice .

Let’s apply this in an example to show how to prepend an element of type int into a slice:

package main

import (
	"fmt"
)

func main() {
	s := []int{1, 2, 3, 4}
	// prepend 0 to s
	s = append([]int{0}, s...)
	fmt.Println(s)
}

Output:

[0 1 2 3 4]