英文:
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 "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)
	    }
    }
}
答案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 := "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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论