为什么我可以在for循环中多次重定义相同的变量,但不能在循环之外? [英] Why I can redefine the same variable multiple times in a for loop but can't outside of a loop?

查看:93
本文介绍了为什么我可以在for循环中多次重定义相同的变量,但不能在循环之外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下程序.

package main

import (
    "fmt"
)

func main() {
    for i := 0; i < 2; i++ {
        x := 77
        fmt.Println(x)
    }
}

执行后,我得到了

77
77

我们可以看到, x:= 77 已经执行了2次.但是,如果我这样修改它:

As we can see, the x := 77 has been execute 2 times. However, If I modify it slightly like this:

package main

import (
    "fmt"
)

func main() {
    a := 77
    fmt.Println(a)
    a := 77
    fmt.Println(a)
}

我将收到错误":= 的左侧没有新变量".为什么会这样?

I will get the error "no new variables on left side of :=". Why this?

推荐答案

这里有几件事.首先,让我们解决您问题的下半部分.

There are a couple of things here. First let's address the second half of your question.

声明变量的默认方法是使用 var 关键字,然后使用 = 运算符将其赋值.

The default way to declare a variable is using the var keyword and then assign to it with the = operator.

var a int
a = 77

Go允许我们使用快捷方式:= 来声明变量和分配值

Go allows us a shortcut := that both declares a variable and assigns a value

a := 77

在您的示例中,当您第二次使用:= 时,您试图在不允许的同一范围内重新声明一个名为 a 的新变量.错误:= 左侧没有新变量正在尝试告诉您.

In your example when you use := a second time you're trying to redeclare a new variable named a in the same scope which is not allowed. The error no new variables on left side of := is trying to tell you this.

但是现在您的原始问题是,为什么您可以在for循环中多次执行此操作?

But now to your original question, why can you do this multiple times inside a for loop?

原因是每次您输入一个大括号 {} 时,您都在创建一个新的嵌套范围.在循环顶部声明变量 x 时,它是一个新变量,在循环结束时超出范围.当程序再次回到循环顶部时,它是另一个新作用域.

The reason is each time you enter a block of curly braces {} you're creating a new nested scope. When you declare the variable x at the top of the loop it is a new variable and it goes out of scope at the end of the loop. When the program comes back around to the top of the loop again it's another new scope.

例如看这段代码

{
    x := 77
    fmt.Println(x)
}
fmt.Println(x) // Compile error

第二个 Println 失败,因为该范围中不存在 x .

That second Println fails because x does not exist in that scope.

这篇关于为什么我可以在for循环中多次重定义相同的变量,但不能在循环之外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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