go variable scope and shadowing

huangapple go评论74阅读模式
英文:

go variable scope and shadowing

问题

这是GOPL中的一个例子:“表达式x[i]和x + 'A' - 'a'分别指向外部块中的x的声明;我们稍后会解释这个。”但是解释从未出现。为什么x[i]引用外部作用域中的x?一旦在内部块中重新声明x,它应该遮蔽外部块中的x。为什么这样能行?

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

英文:

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 &quot;fmt&quot;

func main() {
    x := &quot;hello!&quot;
    for i := 0; i &lt; len(x); i++ {
	    x := x[i]
	    if x != &#39;!&#39; {
		    x := x + &#39;A&#39; - &#39;a&#39;
		    fmt.Printf(&quot;%c&quot;, x)
	    }
    }
}

http://play.golang.org/p/NQxfkTeGzA

答案1

得分: 4

:= 运算符创建一个新变量,并将右侧的值赋给它。

在 for 循环的第一次迭代中,在步骤 x := x[i] 中,右侧看到的唯一的 x 是在步骤 x := "hello!" 中定义的 x。就右侧而言,x 尚未重新声明。

只有在内部块中重新声明 x 之后...

还没有。只有在 x := x[i] 之后才重新声明。

在迭代结束时,新的 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 only x the right hand side sees is the x defined in the step x := &quot;hello!&quot;. 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.

huangapple
  • 本文由 发表于 2015年11月1日 10:09:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/33458547.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定