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
- Golang Program that uses func as Local Variable
- Golang program that uses func with two arguments
- Golang Pointer to an Array as Function Argument
- Atomic Variable in Golang
- How to declare and access pointer variable in Golang?
- Different Ways to Find the Type of Variable in Golang
- How to fetch an Integer variable as String in GoLang?
- Different Ways to Convert an Integer Variable to String in Golang
- Converting a string variable into Boolean, Integer or Float type in Golang
- Golang program that uses fallthrough keyword
- Golang program that uses defer keyword
- Program to shift all zero to the end of array in Golang
- Golang program that uses structs as map keys
- Golang Program that uses String Switch
- Golang Program that Uses Multiple Return Values
- Golang program that uses switch, multiple value cases
- Golang Program that switch on floating-point numbers
- Golang Program to Find Largest Element in an Array
- Golang Program that Removes Duplicates Using Nested Loops
- Golang program that removes duplicates, ignores order
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.