Prepend


Go has a built-in append function which add elements in the slice:

  1. func append(slice []Type, elems ...Type) []Type

But how if we want to the “prepend” effect? Maybe we should use copy function. E.g.:

  1. package main
  2. import "fmt"
  3. func main() {
  4. var s []int = []int{1, 2}
  5. fmt.Println(s)
  6. s1 := make([]int, len(s) + 1)
  7. s1[0] = 0
  8. copy(s1[1:], s)
  9. s = s1
  10. fmt.Println(s)
  11. }

The result is like this:

  1. [1 2]
  2. [0 1 2]

But the above code looks ugly and cumbersome, so an elegant implementation maybe here:

  1. s = append([]int{0}, s...)

BTW, I also have tried to write a “general-purpose” prepend:

  1. func Prepend(v interface{}, slice []interface{}) []interface{}{
  2. return append([]interface{}{v}, slice...)
  3. }

But since []T can’t convert to an []interface{} directly (please refer https://golang.org/doc/faq#convert_slice_of_interface, it is just a toy, not useful.

Reference:
Go – append/prepend item into slice.