Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable length arguments as arguments on another function in Golang?

How to pass variable length arguments in Go? for example, I want to call

func MyPrint(format string, args ...interface{}) {
  fmt.Printf("[MY PREFIX] " + format, ???)
}

// to be called as: MyPrint("yay %d", 213) 
//              or  MyPrint("yay")
//              or  MyPrint("yay %d %d",123,234)
like image 854
Kokizzu Avatar asked Nov 27 '14 11:11

Kokizzu


People also ask

How do you pass variable number of arguments in Golang?

In Golang, it is possible to pass a varying number of arguments of the same type as referenced in the function signature. To declare a variadic function, the type of the final parameter is preceded by an ellipsis, "...", which shows that the function may be called with any number of arguments of this type.

How do you pass an argument to a function in go?

Golang supports two different ways to pass arguments to the function i.e. Pass by Value or Call by Value and Pass By Reference or Call By Reference. By default, Golang uses the call by value way to pass the arguments to the function.

What are variable length arguments explain with suitable example?

You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.


1 Answers

Ah found it...functions that accept variable length arguments are called Variadic Functions. Example:

package main

import "fmt"

func MyPrint(format string, args ...interface{}) {
  fmt.Printf("[MY PREFIX] " + format, args...)
}

func main() {
 MyPrint("yay %d %d\n",123,234);
 MyPrint("yay %d\n ",123);
 MyPrint("yay %d\n");
}
like image 140
Kokizzu Avatar answered Oct 19 '22 12:10

Kokizzu