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 ?
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).
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.