Preend function for all types in go

I wrote 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 } 

In any case, to make a function common to any type?

So, I can add a piece of arrays to it.

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

I did not find anything on the Internet about writing.

+7
go
source share
2 answers

I do not think that you can write such a function in a typical way. But you can use append to add.

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

Playground

+15
source share

How about this:

 // Prepend is complement to builtin append. func Prepend(items []interface{}, item interface{}) []interface{} { return append([]interface{}{item}, items...) } 
0
source share

All Articles