Reputation: 45
This is an example from GOPL - "The expressions x[i] and x + 'A' - 'a' each refer to a declaration of x from an outer block; we'll explain this in a moment."
The explanation never comes. Why is x[i] referring to the x in the outer scope? As soon as you redeclare x in an inner block it should shadow the x in the outer block. Why does this work?
package main
import "fmt"
func main() {
x := "hello!"
for i := 0; i < len(x); i++ {
x := x[i]
if x != '!' {
x := x + 'A' - 'a'
fmt.Printf("%c", x)
}
}
}
http://play.golang.org/p/NQxfkTeGzA
Upvotes: 2
Views: 1560
Reputation: 6531
:=
operator creates a new variable and assigns the right hand side value to it.
At the first iteration of the for loop, in the step x := x[i]
, the only x
the right hand side sees is the x
defined in the step x := "hello!"
. As far as the right hand side sees x
is not redeclared yet.
As soon as you redeclare x in an inner block..
It is not yet. Its redeclared only after x := x[i]
.
And at the end of the iteration the new x
's scope ends. It is not reused in a new iteration.
When a new iteration happens its the same thing all over again.
Upvotes: 4