Golang:函数的多个 return 值的范围

Golang: Scope of multi return values from function

Golang中一个函数returns多个变量时,变量的作用域是什么?在附带的代码中,我无法弄清楚b的范围。

package main

import (
    "fmt"
)

func addMulti(x, y int) (int, int) {
    return (x + y), (x * y)
}

func main() {
    //what is the scope of the b variable here?
    a, b := addMulti(1, 2)

    fmt.Printf("%d %d\n", a, b)

    //what is the scope of the b variable here?
    c, b := addMulti(3, 4)

    fmt.Printf("%d %d\n", c, b)

}   

我们不是在谈论函数的 return 值的范围,而是您将 return 值赋给的变量的范围。

在你的例子中,变量 bscope 是函数体,从你声明它的地方开始。

首先你在这一行做:

a, b := addMulti(1, 2)

但是你在这一行使用另一个 Short Variable declaration:

c, b := addMulti(3, 4)

which - 因为 b 已经被声明 - 只需为其分配一个新值。 b 将在范围内,直到 main() 函数结束。引用自 Go 语言规范:

Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.

它是一个块内的普通变量。来自 the spec:

The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.

在第二次调用中,您只是重新分配同一个 b 变量的值。它的范围是一样的。

b变量的范围是main.main()。在第二个赋值 c, b := addMulti(3, 4) 中引入新变量 c,并赋值在第一个赋值中引入的变量 b。如果将第二个赋值更改为 a, b := addMulti(3, 4) 与第一个相同,则它不想编译。