Home > Article > Backend Development > How to Pass Multiple Return Values as Arguments to Another Function in Go?
How to Use Return Values of One Function as Input Arguments to Another
Problem:
Consider two functions, returnIntAndString and doSomething. returnIntAndString returns two values, an integer and a string, while doSomething takes three arguments: a string, an integer, and another string.
When calling doSomething with the return values of returnIntAndString as arguments, the following error occurs:
main.go:45: multiple-value returnIntAndString() in single-value context main.go:45: not enough arguments in call to doSomething()
Answer:
According to the Go specification, a function call can bind return values of another function to the parameters of the called function only if:
In this case, returnIntAndString returns two values, but doSomething requires a third argument. Therefore, this direct invocation is not allowed.
Alternatives:
There are two alternative solutions:
Create a struct that holds the return values of returnIntAndString and pass an instance of that struct to doSomething.
<code class="go">type ReturnValues struct { I int S string } func returnIntAndString() ReturnValues { return ReturnValues{42, "Hello"} } func doSomething(msg string, values ReturnValues) { // Use values.I and values.S as needed } doSomething("Message", returnIntAndString())</code>
Assign the return values of returnIntAndString to named variables and pass those variables to doSomething.
<code class="go">var i, s = returnIntAndString() doSomething("Message", i, s)</code>
The above is the detailed content of How to Pass Multiple Return Values as Arguments to Another Function in Go?. For more information, please follow other related articles on the PHP Chinese website!