go variable scope and shadowing

2019-07-14 16:25发布

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

标签: go
1条回答
爷、活的狠高调
2楼-- · 2019-07-14 17:06

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

查看更多
登录 后发表回答