-2

Go allows for multiple named return values, but what about the receiving variables? Are they protected when return values are juggled around?

Let's say we start with this:

func foo() (i int, j int) {
   i = 1
   j = 2
   return
}

a, b := foo()

Now what if some other coder comes by and makes the following change to foo's definition:

func foo() (j int, i int) {

my calling function is invalidated. Is it, then, possible to name the returned values from the calling side as well. For instance, if I called it like this:

(a:i, b:j) := foo()

then I would be attaching them to the named return values, rather than assigning them in the order they are returned.

So, is there a way to solve that problem?

BrandG
  • 66
  • 1
  • 8
  • 2
    *"Is it, then, possible to name the returned values from the calling side as well."* No, it isn't possible. *"So, is there a way to solve that problem?"* the only thing I can think of are unit tests and documentation. – mkopriva Jul 19 '19 at 17:14
  • Related / possible duplicate of [Initialize function fields](https://stackoverflow.com/questions/48153929/initialize-function-fields/48154019?r=SearchResults#48154019). – icza Jul 19 '19 at 17:20

1 Answers1

1

This is no different than rearranging the input parameters. As a rule, don't do that unless you intend to make a breaking change. But if you want to deal with things by name rather than position, you want a struct. For example, you can use anonymous structs:

func foo() struct {
    i int
    j int
} {
    return struct {
        i int
        j int
    }{1, 2}
}

func main() {
    result := foo()
    fmt.Println(result.i, result.j)
}

Of course you can also name the struct if you used it in other places, but there's no need if you just want to name the fields.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610