为什么可以使用 for 循环声明同一个变量两次?

Why is it possible to declare the same var two times using for-loop?

我正在尝试继续 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 := ... will overshadow the same variable declared outside of the scope of the for loop 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.

一个简短的变量声明可以在块内重新声明相同的变量,但是由于 i 也在 for 块的 外部 声明,它保持它的值在所述块之外(different scope).

第一个 i 是在 main 函数的大括号 ({}) 内定义的,而第二个 i 是在 for 循环的范围内声明的。名称相同但作用域不同