Home > Software engineering >  Golang - using function with multiple return values in a return statement
Golang - using function with multiple return values in a return statement

Time:02-11

If I have an "inner"/nested function in Go:

    findDups := func(groups []string) (int, string) {
        dupCnt := 0
        dups := ""
        prevGroup := ""
        for _, group := range groups {
            if group == prevGroup {
                dupCnt  
                dups  = group   ", "
            }
            prevGroup = group
        }
        return dupCnt, dups
    }

Is there a way in the language where I can call this function from the "outer"/parent function's return statement, e.g.:

return findDups(sourceGroups), findDups(targetGroups)

The parent function's return signature is (int, string, int, string). The compiler is complaining with the message:

2-valued findDups(sourceGroups) (value of type (int, string)) where single value is expected

I can deal with this by just creating four variables with the return values from the two calls to the inner function and using them in the return statement, but wondered if there's a more direct way of doing this. I've tried Googling it but can't seem to form the right question.

CodePudding user response:

The spec is pretty clear on what your options are (emphasis mine):

  1. The return value or values may be explicitly listed in the "return" statement.
  2. The expression list in the "return" statement may be a single call to a multi-valued function.
  3. The expression list may be empty if the function's result type specifies names for its result parameters.
  • Related