"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-23
Browse:679

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:

func returnIntAndString() (i int, s string) {...}
func doSomething(i int, s string) {...}

doSomething(returnIntAndString())

However, complications arise when you add an additional argument to the second function:

func doSomething(msg string, i int, s string) {...}
doSomething("message", returnIntAndString()) // Error

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:
func doSomethingVariadic(msg string, args ...interface{}) {
  // Code to handle variable number of arguments
}

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

doSomethingVariadic("message", returnIntAndString())
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3