0

I have the following Golang code:

rows, err := common.GetAll(c, req, params, timer)
return common.GenericRowMarshal(200, rows, err)

I want to figure out if it's possible to do:

return common.GenericRowMarshal(200, common.GetAll(c, req, params, timer)...)

but this doesn't compile :(

It says "not enough arguments to call..."

Anyone know if this is possible somehow?

  • 2
    In this special case you can't. If parameters would match with the return types exacty, you could. You could also do it if the callable function would have a final variadic parameter, see [how to parse multiple returns in golang](https://stackoverflow.com/questions/52653779/how-to-parse-multiple-returns-in-golang/52654950#52654950). – icza Feb 24 '20 at 08:24
  • The params do match the return types tho..I think you mean *all the params* of the func to be called (outer func) have to match the inner func return values. –  Feb 24 '20 at 09:27

2 Answers2

4

No, each time a statement executes, the function value and parameters to the call are evaluated as usual, see doc:

As a special case, if the return values of a function or method g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(parameters_of_g)) will invoke f after binding the return values of g to the parameters of f in order. The call of f must contain no parameters other than the call of g, and g must have at least one return value. If f has a final ... parameter, it is assigned the return values of g that remain after assignment of regular parameters.

func Split(s string, pos int) (string, string) {
    return s[0:pos], s[pos:]
}

func Join(s, t string) string {
    return s + t
}

if Join(Split(value, len(value)/2)) != value {
    log.Panic("test fails")
}

If f has a final ... parameter, it is assigned the return values of g that remain after assignment of regular parameters.

For example, the following code works:

package main

import "fmt"

func main() {
    f(200, g())
}
func f(i int, slice ...interface{}) {
    fmt.Println(i, slice) // 200 [[1 <nil>]]
}
func g() []interface{} {
    return []interface{}{1, nil}
}
wasmup
  • 14,541
  • 6
  • 42
  • 58
-1

I've tried this too, thinking it might work. Currently (Go 1.13) you can only do this if the inner func returns exactly the parameters that the outer function expects.

Andrew W. Phillips
  • 3,254
  • 1
  • 21
  • 24