Passing Multiple Return Values to Variadic Functions in Go
Question:
Can a function returning multiple integer values be directly passed into fmt.Println() for formatted string output, similar to Python?
func temp() (int, int) { return 1, 1 } fmt.Println("first= %d and second = %d", temp()) // Not supported
Answer:
No, this is not directly supported by default in Go. According to the language specification, "Calls" expects a function call as the sole argument for variadic parameters like ...interface{}, and functions must have at least one return value.
fmt.Printf(), however, allows for a format string alongside the variadic parameter, making it more suitable for this task. However, since temp() returns a tuple, it cannot be directly passed as a ...interface{} argument.
Solution:
To pass multiple return values into a variadic function, a utility wrapper function can be used to convert the tuple into a []interface{} slice, which can then be passed as the variadic argument. Below is an example implementation:
func wrap(vs ...interface{}) []interface{} { return vs }
Using this wrapper function, the temp() function can now be passed into fmt.Printf():
func main() { fmt.Printf("first= %v and second = %v", wrap(temp()...)...) }
This will properly print the values of temp().
The above is the detailed content of Can Go's `fmt.Println` Handle Multiple Return Values from a Function Directly?. For more information, please follow other related articles on the PHP Chinese website!