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

标签 variables for-loop go var variable-declaration

我正在尝试继续 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/

相关文章:

javascript从数组中获取第二个变量

java - 如何从我拥有的对象中获取变量?

android - 将一个从适配器类动态变化的整数变量传递给 Activity

Python - 赋值前引用的变量

php - 遍历数据库查询

java - 如何只在for循环中的所有条件都为真时才返回true?

bash循环遍历子目录中的所有查找

go - Go 中的元组赋值

windows - 我想在 Windows 上使用 Go 开发并部署到 Google App Engine

go - 使用 "var"声明一个新的结构实例与在 Go 中使用 "new"有何不同?