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)
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.
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.
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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With