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)
}
}
}
:=
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 onlyx
the right hand side sees is thex
defined in the stepx := "hello!"
. As far as the right hand side seesx
is not redeclared yet.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.