Variadic Functions in Go
Variadic Functions
50
In Go, a variadic function is a function that can accept a varying number of arguments. It is denoted by using the ellipsis ("...") before the type of the last parameter of the function. In other words, a variadic function can accept zero or more arguments of a particular type.
Here is an example of a variadic function in Go:
func add(numbers ...int) int { sum := 0 for _, num := range numbers { sum += num } return sum }
The function add()
accepts any number of integer arguments and returns their sum.
We can call this function with one or more integer values like below:
total := add(2, 3, 4, 5) // total is 14
It is also possible to pass a slice of integers to a variadic function using the spread operator ('...'), like so:
nums := []int{1, 2, 3} total := add(nums...) // total is 6
Variadic functions are quite useful when you want to write a function that can operate on multiple arguments, without knowing ahead of time how many of them there will be. They can be used for tasks such as calculating the total sum of a list of numbers or concatenating multiple strings.
March 27, 2023