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.
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.
How about this:
// Prepend is complement to builtin append.
func Prepend(items []interface{}, item interface{}) []interface{} {
return append([]interface{}{item}, items...)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With