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
Release: 2024-11-01 03:23:27
Original
907 people have browsed it

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

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

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

You can then call this function with the desired arguments, including the return values of returnIntAndString():

<code class="go">doSomethingVariadic("message", returnIntAndString())</code>
Copy after login

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!

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