Golang program that uses func with variable argument list
In Golang, a function that can be called with a variable argument list is known as a variadic function. One can pass zero or more arguments in the variadic function. If the last parameter of a function definition is prefixed by ellipsis …, then the function can accept any number of arguments for that parameter.
Syntax of a variadic function:
func f(elem ...Type)
Here ...
operator tells Golang program to store all arguments of Type in elem parameter. After that, Go create an elem variable of the type []Type. Therefore, all the values passed are stored in an elem parameter which is a slice. A slice can also be passed in the argument instead of the argument list, as finally function is converting them into a slice. For more information you can refer to Variadic Functions in Golang
Advantages of using a Variadic Function:
- Passing a slice in a function is very easy.
- Useful when the number of parameters is unknown.
- Increases the readability of the program.
Let’s see some of the examples to use functions with variable argument list:
Example 1:
Go
// Go program that uses a function
// with variable argument list
package main
// Importing required packages
import (
"fmt";
)
// Variadic function to return
// the sum of the numbers
func add(num ...int) int {
sum := 0
for _, j := range num {
sum += j
}
return sum
}
func main() {
fmt.Println("Sum =", add(1, 2, 3, 4, 5, 7, 8, 6, 5, 4))
}