Go Variadic Functions
Functions generally accept a fixed number of arguments. A Variadic function is a function that accepts a variable number of arguments. In simple terms, variadic function accepts infinite arguments.
Variadic Function Example
Instead of explicitly using an array, we can sometimes use functions with a variable number of arguments.
You already encountered them when using fmt.Println
(and similar functions):
package main
import "fmt"
func main() {
// The println here can accept infinite values
fmt.Println("Hello", "world")
fmt.Println("Hello", "world", "!")
fmt.Println("Welcome", "to", "Go", "Programming", "!!!")
}
How to define a variadic function?
To define a variadic function, you have to add an ellipsis (...
) before the type of the last argument:
Syntax
func myFunction(arg1 type1, arg2 type2, arg3 ...type3) (returnType) {
// function body
}
- The
...
with type prefixed in the final argument is called variadic - The variadic parameter in the function signature indicates that it can accept zero, one, or more values. In the above syntax,
arg3
parameter is variadic - Variadic parameters can make your code more readable
- The function can have only one variadic parameter, which must be the last parameter defined in the function.
- You can pass one or more slices in the variadic function
Let us look at some use cases where we can use the variadic functions.
Example 1: Find the average
of numbers using variadic function
Let's define another average
function that takes a variable number of arguments:
package main
import "fmt"
func average(numbers ...float64) float64 {
var sum float64
for _, number := range numbers {
sum += number
}
return sum / float64(len(numbers))
}
func main() {
fmt.Println(average(1, 2, 3, 4, 5))
}
Note: The fact that you can iterate over ...
and compute the length of ...
is possible because under the hood, ...
is an array.
Example 2: Find the max
value in a given set of numbers
Let's define a variadic function that returns the maximum of a variable number of arguments:
package main
import "fmt"
func max(numbers ...int) int {
var max int
for _, number := range numbers {
if number > max {
max = number
}
}
return max
}
func main() {
fmt.Println(max(1, 2, 3, 4, 5))
}
When to use variadic functions?
- If the number of input parameters is unknown
- If you are creating a temporary slice just to pass to a function.
- If the arguments to your function are not likely to come from a single data structure
- To make the code more readable.
As a rule of thumb, you should use explicit arrays when you don't have access to all the parameters independently and variadic functions when you do.