Background:
Go functions can return multiple values, but standard variadic function calls do not allow for passing those values directly. This article explores a method to achieve this using a custom wrapper function.
Problem:
Consider a function that returns two integer values:
func temp() (int, int) { return 1, 1 }
We want to pass these return values to the variadic Printf function to print them using string formatting:
fmt.Printf("first= %d and second = %d", temp()) // Error
Solution:
1. Direct Approach (Not Supported):
The standard function call syntax does not support passing multiple return values to a variadic function. This is because variadic parameters must be the last parameters in a function signature.
2. Wrap Return Values:
We can create a wrapper function that converts the return values of any function into a []interface{} slice. The variadic Printf function can then accept this slice as its arguments.
func wrap(vs ...interface{}) []interface{} { return vs }
Usage:
Using the wrap function, we can now pass the return values of our temp function to Printf:
fmt.Printf("first= %d and second = %d", wrap(temp()...)...)
Additional Notes:
The above is the detailed content of How to Pass Multiple Go Function Return Values to a Variadic Function?. For more information, please follow other related articles on the PHP Chinese website!