Open In App

Variadic Functions in Go

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...}

Example 1: 






// 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 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: 


Article Tags :