英文:
Lexical scoping in golang?
问题
我不太明白为什么最后a不是2:
func main() {
z := 4
if true {
z := 2
fmt.Println(z)
}
fmt.Println(z) // 输出4
}
英文:
I don't quite understand why a is not 2 at the end:
func main (){
z := 4
if true {
z := 2
fmt.Println(z)
}
fmt.Println(z) // prints 4
}
答案1
得分: 11
z正在被屏蔽。将:=更改为=,它就会正常工作。
func main() {
z := 4
if true {
z = 2
fmt.Println(z)
}
fmt.Println(z) // 输出 2
}
if语句有它自己的作用域,当你使用:=时,你声明了一个新变量并屏蔽了旧变量。
英文:
z is getting shadowed. Change := to = and it will work.
func main (){
z := 4
if true {
z = 2
fmt.Println(z)
}
fmt.Println(z) // prints 2
}
The if statement has its own scope, when you used := you declared a new variable and shadowed the old one.
答案2
得分: 0
这甚至无法编译(我是在回答未编辑版本的问题)。
你需要使用分号 ; 而不是逗号:
func main() {
a := 0
for i := 0; i < 10; i++ {
a += 5
}
fmt.Println(a) // 输出 50
}
英文:
This does not even compile (I was answering the unedited version of the question).
You have to use ; instead of ,:
func main(){
a := 0
for i := 0; i < 10; i++ {
a += 5
}
fmt.Println(a) // prints 50
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论