Variadic Parameter

Functions that take a variable number of parameters are known as variadicfunctions. To declare a function as variadic, dosomething like this:

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

The arg …int instructs Go to see this as a function that takes a variablenumber of arguments. Note that these arguments all have to have the type int.In the body of your function the variable arg is a slice of ints:

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

We range over the arguments on the first line. We are not interested in theindex as returned by range, hence the use of the underscore there. In the bodyof the range we just print the parameters we were given.

If you don’t specify the type of the variadic argument it defaults to the emptyinterface interface{} (see Chapter ).

Suppose we have another variadic function called myfunc2, the followingexample shows how to pass variadic arguments to it:

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

With myfunc2(arg…) we pass all the parameters to myfunc2, but because thevariadic parameters is just a slice, we can use some slice tricks as well.