Home > Backend Development > Golang > 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
Release: 2024-10-31 08:49:02
Original
579 people have browsed it

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()
Copy after login

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>
Copy after login
  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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template