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)
... 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:
Sum = 45
Example 2: A slice can also be used as an argument list.
Element 1 found at index: 1 Element not present in the list
Please Login to comment...