去变量范围和阴影 [英] go variable scope and shadowing

查看:109
本文介绍了去变量范围和阴影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是GOPL的一个例子 - 表达式x [i]和x +'A' - 'a'分别指向外部块的x声明,我们稍后会解释。



这个解释永远不会出现。为什么x [i]指向外部范围中的x?只要你在一个内部块中重新声明x,它应该在外部块中遮蔽x。为什么这样做?

 包主

导入fmt

func main(){
x:=hello!
for i:= 0;我< LEN(X);如果x!='!'{
x:= x +'A' - 'a'
fmt.Printf(%c ,x)
}
}
}

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

解决方案

:= 运算符创建一个新变量并为其赋予右侧值。

在for循环的第一次迭代中,在步骤 x:= x [i] 中,唯一的 x 右手边是在步骤 x:=hello中定义的 x 。至于右边看到 x 还没有被重新声明。


只要您在内部块中重新声明x就可以了。

尚未。它仅在 x:= x [i] 之后重新声明。



在迭代结束时,新的 x 的作用域结束。它不会在新的迭代中重复使用。



当新的迭代发生时,它会再次发生同样的事情。


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

解决方案

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

这篇关于去变量范围和阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆