The function that is called with the varying number of arguments is known as variadic function. Or in other words, a user is allowed to pass zero or more arguments in the variadic function. fmt.Printf is an example of the variadic function, it required one fixed argument at the starting after that it can accept any number of arguments.
Important Points: In the declaration of the variadic function, the type of the last parameter is preceded by an ellipsis, i.e, (…). It indicates that the function can be called at any number of parameters of this type.
Syntax:
function function_name(para1, para2...type)type {// code...}
- Inside the function …type behaves like a slice. For example, suppose we have a function signature, i.e, add( b…int)int, now the parameter is of type []int inside the function.
- You can also pass an existing slice in a variadic function. To do this, we pass a slice of the complete array to the function as shown in Example 2 below.
- When you do not pass any argument in the variadic function, then the slice inside the function is empty.
- The variadic functions are generally used for functions that perform string formatting.
- You can also pass multiple slices in the variadic function.
- You can not use variadic parameter as a return value, but you can return it as a slice.
Example 1:
Go
// Go program to illustrate the // concept of variadic function package main import ( "fmt" "strings" ) // Variadic function to join strings func joinstr(elements ... string ) string { return strings.Join(elements, "-" ) } func main() { // zero argument fmt.Println(joinstr()) // multiple arguments fmt.Println(joinstr( "GEEK" , "GFG" )) fmt.Println(joinstr( "Geeks" , "for" , "Geeks" )) fmt.Println(joinstr( "G" , "E" , "E" , "k" , "S" )) } |
Output:
GEEK-GFG Geeks-for-Geeks G-E-E-k-S
Note: The first line of the output is empty because in the program we first call our function joinstr without any arguments (i.e. the zero argument case) due to which it returns an empty string.
Example 2:
Go
// Go program to illustrate the // concept of variadic function package main import ( "fmt" "strings" ) // Variadic function to join strings func joinstr(elements ... string ) string { return strings.Join(elements, "-" ) } func main() { // pass a slice in variadic function elements := [] string { "geeks" , "FOR" , "geeks" } fmt.Println(joinstr(elements...)) } |
Output:
geeks-FOR-geeks
When we use a Variadic function:
- Variadic functions can be used instead of passing a slice to a function.
- Variadic function is used when we don’t know the number of parameters.
- When you use variadic function in your program, it increases the readability of your program.
- Variadic functions are especially useful when the arguments to your function are most likely not going to come from a single data structure (i.e. slice or array etc.).
- In such cases using variadic functions avoids the creation of a data structure to just pass in the arguments to a function.