Home >Backend Development >Golang >How to Pass Multiple Return Values from One Function to Another in Go?

How to Pass Multiple Return Values from One Function to Another in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 03:23:27885browse

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:

  1. Assign Return Values to Separate Variables: Assign the return values of returnIntAndString() to individual variables and pass them as arguments to doSomething().
  2. Use a Function that Accepts Variadic Arguments: If you need to pass additional arguments, you can define a function that accepts variadic arguments, as seen in the example below:
<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!

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