Home >Backend Development >Golang >How to Handle Multiple Return Values When Passing to Variadic Functions in Go?
Multiple Return Values with Variadic Functions
Suppose you have a Go function that returns multiple integer values, such as:
func temp() (int, int) { return 1, 1 }
Intuitively, you might want to directly pass the result of temp to Printf and print both values using string formatting:
fmt.Printf("first= %d and second = %d", temp())
However, this approach does not work because temp returns two values, while Printf expects only one.
The reason for this limitation lies in the Go function call specification. It states that if a function has a final ... parameter (as Printf does), it can only be assigned the remaining return values of another function. This implies that the other function must have at least one return value.
Using String Interpolation
Instead of using Printf, you can leverage string interpolation to achieve your goal:
a, b := temp() fmt.Println("first=", a, "and second =", b)
Wrapping Return Values
To pass multiple return values to a variadic function like Printf, you can utilize a utility function called wrap. It takes an arbitrary number of interface{} values and returns a slice of interface{} values:
func wrap(vs ...interface{}) []interface{} { return vs }
With this utility, you can pass the return values of any function that has at least one return value to wrap and use the resulting slice to call Printf:
fmt.Printf("1: %v, 2: %v\n", wrap(oneInt())...) fmt.Printf("1: %v, 2: %v\n", wrap(twoInts())...) fmt.Printf("1: %v, 2: %v, 3: %v\n", wrap(threeStrings())...)
where oneInt, twoInts, and threeStrings are functions returning single integers, tuples of integers, and tuples of strings, respectively.
This approach bypasses the restriction of passing only one return value to variadic functions, allowing you to print the multiple return values of your functions as desired.
The above is the detailed content of How to Handle Multiple Return Values When Passing to Variadic Functions in Go?. For more information, please follow other related articles on the PHP Chinese website!