We already saw the “normal” way to return values from functions… But did you know there’s a shortcut if you ever want to directly return the values returned from another function?
Return statements
…
- The expression list in the “return” statement may be a single call to a multi-valued function. The effect is as if each value returned from that function were assigned to a temporary variable with the type of the respective value, followed by a “return” statement listing these variables, at which point the rules of the previous case apply.
func complexF2() (re float64, im float64) { return complexF1() }
I use this pretty frequently.
However, note that you cannot mix this with other return values. To demonstrate what I mean, here’s an example that’s not valid.
func foo() (string, string) { /* ... */ }
func bar() (string, string, error) {
/* some logic */
return foo(), nil
}
The shortcut only works when the multi-valued function is the only thing being returned. So in this example, we need to use our own explicit temporary variables:
a, b := foo()
return a, b, nil
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)