Go Variadic Functions

Go Variadic Functions

Like in Python, the functions that can take each time a variable number of parameters are known as variadic functions. To declare a variadic function we can write something like this:

func myfunc(arg ...int) {}

The arg ...int here indicates that this function can take a variable number of arguments, and all of these arguments must be an integer type. If you don’t specify the type of the variadic argument it defaults to the empty interface interface{} like:

func myfunc(arg ...interface{}) {}

After this, we can use iterate over arg parameter inside our function like this:

for _, n := range arg {
    fmt.Printf("And the number is: %d\n", n)
}

We can call this method basically like this:

func main() {
	myfunc(1)
	myfunc(1, 2, 3)
	myfunc(1, 2, 3, 4, 5)
}

The parameter arg is an instance of a slice, not an array or something else. If we want to use pass an array to this function, we need to unpack the array into a slice before like:

func main() {
	nums := []int{1, 2, 3, 4}
	myfunc(nums...)
}

Another important point, let’s say we have a second variadic function called func2:

func myfunc2(arg ...int) {}
func myfunc(arg ...int) {}

If we need to call myfunc2 with the passed arg parameters, either we can pass the whole argument by unpacking or we can slice and then unpack.

func myfunc(arg ...int) {
    myfunc2(arg...)
    myfunc2(arg[:2]...)
}

Another point is, suppose we have two variables one of them integer and the other one is a slice:

func myfunc(arg ...int, a int) {}

We won’t be able to pass a parameter to a variable a because all of them will be passed into arg. So we can only use as the final argument in the list like:

func myfunc(a int, arg ...int) {}

Resources:
Go by Example: Variadic Functions
Variadic Functions