In this lesson, let’s learn about variadic functions. These are functions which take variable number of arguments.

Variadic functions are functions which accept variable number of arguments of the same type.

  • These functions accept variable number of arguments.
  • Note that the arguments must be of the same data type.
  • For declaring variadic function, the type parameter is preceded by elipsis (...). The variadic argument will be stored in a slice.

We have seen few examples of this already like fmt.Println or append function we have seen which takes multiple arguments of the same type. One limitation of this type of functions is that this parameter must be at the end of the function. So, we cannot have a function like this because the parameter which can take multiple values is defined in the middle.

1func incorrect(a int, b ...int, c float32) int {}

However, below function declaration will be acceptable.

1func correct(a int, c float32, b ...int) int {}

Let’s define a sum function which can sum variable number of arguments.

Example:

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6	fmt.Println(sum(1, 2, 3))
 7	fmt.Println(sum())
 8	fmt.Println(sum(1, 2, 3, 4, 5))
 9}
10
11func sum(numbers ...int) (sum int) { // named return value
12	sum = 0
13	for _, number := range numbers {
14		sum += number
15	}
16	return
17}

As we can see, we can pass any number of arguments to the sum function. Output:

6
0
15

Let’s define another function which can take variable number of guests and greet them with a message.

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6	greetings("Good morning", "John", "Jenny", "Jessica")
 7	greetings("Good bye", "John", "Jenny", "Jessica")
 8}
 9
10func greetings(greeting string, guests ...string) {
11	for _, guest := range guests {
12		fmt.Println(greeting, guest)
13	}
14}

Output:

Good morning John
Good morning Jenny
Good morning Jessica
Good bye John
Good bye Jenny
Good bye Jessica