"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 ​​as parameters to a function in Go?

How to pass multiple return values ​​as parameters to a function in Go?

Posted on 2025-04-13
Browse:223

How to Pass Multiple Return Values as Arguments to Functions in Go?

Return Values as Arguments to Multi-Argument Functions

When dealing with functions that return multiple values, it's possible to use these values as input arguments to other functions. However, certain limitations apply when the receiving function has additional parameters.

Consider the following code:

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

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

If we attempt to pass the return values of returnIntAndString() to doSomething() directly:

doSomething("message", returnIntAndString())

Go will complain with the errors:

multiple-value returnIntAndString() in single-value context
not enough arguments in call to doSomething()

This is because Go only allows passing a single value as an argument to a function, even if the return value of the previous function yields multiple values.

To resolve this issue, you have two options:

  1. Assign Return Values:
    Assign the return values to temporary variables and pass them individually to doSomething().

    i, s := returnIntAndString()
    doSomething("message", i, s)
  2. Return Specific Values:
    In the returnIntAndString() function, return a named struct with fields for each value. Then, pass the struct to doSomething().

    type Result struct {
       I int
       S string
    }
    
    func returnIntAndString() Result {...}
    
    res := returnIntAndString()
    doSomething("message", res.I, res.S)

Remember, Go's specific rules do not allow additional parameters alongside a multi-value return value function when assigning arguments. If the specific conditions outlined in the language specification are not met, you must employ one of the provided solutions.

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