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.

  • The syntax for the variadic function isHere, we see that the type of the last parameter is preceded by the ellipsis symbol (...) which indicates that the function can take any number of parameters if the type is specified.
  • Inside the variadic function, the ... type can be visualised as a slice. We can also pass the existing slice (or MULTIPLE slices) of the mentioned type to the function as a second parameter. When no values are passed in variadic function, the slice is treated as nil.
  • These functions are GENERALLY used for string formatting.
  • Variadic parameter can not be specified as return value, but we can return the variable of type slice from the function.

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


Discussion

No Comment Found