我正在尝试继续 http://tour.golang.org/ ,并且我看到可以在 for 循环中使用 := 声明两次相同的 var。 输出与 Go 编译器相同。
这是我的测试:(查看 var i,它被声明了两次)
package main
import "fmt"
func main() {
i := "Hello"
a := 0
for a < 2 {
fmt.Println(i)
i := "World !"
fmt.Println(i)
a++
}
}
输出:
Hello
World !
Hello
World !
谁能解释一下?
最佳答案
short variable declaration i := ...
将覆盖在 for
循环 block 范围之外声明的同一变量。
Each "
if
", "for
", and "switch
" statement is considered to be in its own implicit block
你可以在“Go gotcha #1: variable shadowing within inner scope due to use of :=
operator”看到更多
指的是这个goNuts discussion。
一个简短的变量声明可以在一个 block 内重新声明同一个变量,但是由于 i
也在 for block 的外声明,它保持它的值在所述 block 外( different scope ).
关于variables - 为什么可以使用 for 循环声明同一个变量两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32778088/