2

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

VM7
  • 45
  • 7

1 Answers1

4

:= 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.

Aruna Herath
  • 6,241
  • 1
  • 40
  • 59
  • 1
    Ah so each iteration of the loop is a new scope. http://stackoverflow.com/questions/7880658/what-is-the-scope-of-a-while-and-for-loop – VM7 Nov 01 '15 at 04:47