Home  >  Article  >  Backend Development  >  How to Pass Multiple Return Values as Arguments to Another Function in Go?

How to Pass Multiple Return Values as Arguments to Another Function in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 08:49:02463browse

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:

  • The number of return values of the first function is equal to the number of parameters for the second function.
  • The types of the return values are assignable to the types of the parameters.

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:

  1. Wrap the Return Values in a Struct:

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>
  1. Assign Return Values to Separate Variables:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn