A variadic function accepts a varying number of arguments.
The ordinary function takes a fixed number of arguments, but we often need a variadic function.
For example, fmt.Println
is a variadic function, so it can accept any number of arguments.
We can define a variadic function by using an ellipsis ( . . .
), like . . . T in front of the last parameter in the function signature.
func (someType ...T)
We want a function, sum1
, that computes the average of an arbitrary number of integers.
We can use the following signature for this function:
func (nums ...int) int
Take a look below for the full implementation of function sum1
, below.
package mainimport "fmt"func sum1(nums ...int) int {total := 0for _, num := range nums {total += num}return total}func main() {fmt.Println(sum1()) // with zero (empty) argumentfmt.Println(sum1(1, 2)) // more than zero argument}
Now, our requirement is slightly changed. We want a function sum2
that takes at least one integer and calculates the sum.
To solve this, we can use the first argument as a fixed argument, followed by a variadic parameter.
package mainimport "fmt"func sum2(num1 int, nums ...int) int {total := num1for _, num := range nums {total += num}return total}func main() {fmt.Println(sum2()) // gives errorfmt.Println(sum2(0))fmt.Println(sum2(1, 2, 3, 4, 5))}
Try commenting line
14
to successfully run the program above.
We can also pass slice S []T
as an argument to . . . T
, using syntax S . . .
to unpack slice elements.
Suppose we have a slice S
of integer:
S := []int{1,2,3,4,5}
We can pass slice S
to sum1
and sum2
, as shown:
package mainimport "fmt"func sum1(nums ...int) int {total := 0for _, num := range nums {total += num}return total}func sum2(num1 int, nums ...int) int {total := num1for _, num := range nums {total += num}return total}func main() {S := []int{1,2,3,4,5}fmt.Println(sum1(S...))// first argument should be normalfmt.Println(sum2(0, S...))}
As we have seen, a variadic function is an inevitable feature of any programming language as it provides versatility.