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 ...
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...}
Here is one example
// 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"))
}