英文:
Why is it possible to declare the same var two times using for-loop?
问题
我正在为您翻译以下内容:
我正在尝试在http://tour.golang.org/上使用Go语言,并且我发现在for循环中可以使用:=声明两次相同的变量。
输出结果与Go编译器相同。
以下是我的测试代码:(请注意变量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 !
有人可以解释一下这是为什么吗?
英文:
I was trying Go on http://tour.golang.org/, and I saw that it was possible to declarate two times the same var using := in for loop.
The output is the same with the Go compiler.
Here is my test : (see the var i, it was declared two times)
package main
import "fmt"
func main() {
i := "Hello"
a := 0
for a < 2 {
fmt.Println(i)
i := "World !"
fmt.Println(i)
a++
}
}
Output :
> Hello
>
> World !
>
> Hello
>
> World !
Can someone explain that ?
答案1
得分: 4
短变量声明 i := ...
会遮盖在 for
循环的**块**之外声明的同名变量。
> 每个“if
”、“for
”和“switch
”语句都被视为自己的隐式块。
你可以在“Go gotcha #1: variable shadowing within inner scope due to use of :=
operator”中了解更多信息。
它参考了这个goNuts讨论。
短变量声明可以在一个块内重新声明同名变量,但由于 i
也在 for
块之外声明了(不同的作用域),它在该块之外保持其值。
英文:
The 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
You can see more at "Go gotcha #1: variable shadowing within inner scope due to use of :=
operator"
It refers to this goNuts discussion.
A short variable declaration can redeclare the same variable within a block, but since i
is also declared outside the for block, it keeps its value outside said block (different scope).
答案2
得分: 1
第一个i在main函数的大括号({})内部定义,而第二个i在for循环的作用域内声明。名称相同,但作用域不同。
英文:
The first i has been defined inside the braces ({}) of main function wheras the second i is declared within the scope of the for loop. The name is same but the scope is different.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论