Search code examples
goslicepolyvariadic

Variadic generic arguments in Go


Let's say I want to make the equivalent of the JavaScript Array.splice function in Go, for Slices. I have the following code:

func splice(slice []int, index, amount int, elements ...int) []int {
    newslice := make([]int, 0)
    for i := 0; i < index; i++ {
        newslice = append(newslice, slice[i])
    }
    for i := index + amount; i < len(slice); i++ {
        newslice = append(newslice, slice[i])
    }
    for _, el := range elements {
        newslice = append(newslice, el)
    }
    return newslice
}

This example will work, but only for arguments of type int. I want to make it generic, and I know that I should give the variadic argument elements the type interface{}, but how do I create a new slice with the type of that interface from inside the function?

In other words, how can I specify the type of the slice dynamically depending on the type of the arguments in the first line of the function, where newslice is created?


Solution

  • Instead of emulating JavaScript in Go (why ???) I would like to suggest to compose simmilar required operations from the building blocks of SliceTricks.

    They are:

    • Completely type agnostic (think "generics" for free).
    • Quite probably pretty faster compared to packing/unpacking whatsoever in/from a []interface{}.