Home >Backend Development >Golang >How to Pass Multiple Return Values from One Function to Another in Go?
Passing Function Return Values as Inputs to Another Function
In Go, you can conveniently pass the return values of one function as input arguments to another function. For example:
<code class="go">func returnIntAndString() (i int, s string) {...} func doSomething(i int, s string) {...} doSomething(returnIntAndString())</code>
However, complications arise when you add an additional argument to the second function:
<code class="go">func doSomething(msg string, i int, s string) {...} doSomething("message", returnIntAndString()) // Error</code>
The error message indicates that you cannot pass multiple return values to a function expecting a single argument.
Solution
As per the Go specification, a function can only pass its return values as input arguments to another function if the latter expects the exact same number of arguments. There is no mechanism for passing extra parameters in this scenario.
Therefore, to resolve the issue, you have two options:
<code class="go">func doSomethingVariadic(msg string, args ...interface{}) { // Code to handle variable number of arguments }</code>
You can then call this function with the desired arguments, including the return values of returnIntAndString():
<code class="go">doSomethingVariadic("message", returnIntAndString())</code>
The above is the detailed content of How to Pass Multiple Return Values from One Function to Another in Go?. For more information, please follow other related articles on the PHP Chinese website!