Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang – using function with multiple return values in a return statement

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading