Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prepend function for all types in go

Tags:

go

I have written a very small prepend function for go.

func prepend(slice []int, elms ... int) []int {

   newSlice := []int{}

   for _, elm := range elms {
      newSlice = append(newSlice, elm)
   }

   for _, item := range slice {
      newSlice = append(newSlice, item)

   }

   return newSlice
}

Is there anyway to make the function generic for any type?

So that I can put in a slice of arrays a prepend to that.

Also, is there a better way to write this function?

I have not found anything online about writing one.

like image 355
biw Avatar asked Aug 02 '14 07:08

biw


2 Answers

I don't think you can write such function in a type-generic way. But you can use append to prepend as well.

c = append([]int{b}, a...)

Playground.

like image 89
Ainar-G Avatar answered Nov 19 '22 11:11

Ainar-G


How about this:

// Prepend is complement to builtin append.
func Prepend(items []interface{}, item interface{}) []interface{} {
    return append([]interface{}{item}, items...)
}
like image 1
Luke W Avatar answered Nov 19 '22 11:11

Luke W