| 1. |
What do you understand by variadic functions in Go? |
|
Answer» The function that takes a variable number of arguments is called a variadic function. We can pass zero or more PARAMETERS in the variadic function. The best example of a variadic function is fmt.Printf which requires one fixed argument as the first parameter and it can accept any arguments.
Consider an example code below: FUNC function_name(arg1, arg2...type)type{ // Some statements}package main import( "fmt" "strings") // Variadic function to join strings and separate them with hyphenfunc joinstring(element...string)string{ return strings.Join(element, "-")} func main() { // To demonstrate zero argument fmt.Println(joinstring()) // To demonstrate multiple arguments fmt.Println(joinstring("Interview", "Bit")) fmt.Println(joinstring("Golang", "Interview", "Questions")) }Here, we have a variadic function called joinstring that takes a variable number of arguments of a type string. We are trying to join the arguments separated by the hyphen symbol. We are demonstrating the variadic function behaviour by first passing 0 arguments and then passing multiple arguments to the function. The output of this code is: Interview-BitGolang-Interview-Questions |
|