命名来自多重返回函数的接收变量

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?

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.