dougu8742 2016-08-29 14:00
浏览 271
已采纳

在Golang中,为什么我可以在for循环中多次重定义相同的变量,但是不能在循环之外?

I have the following program.

package main

import (
    "fmt"
)

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

When executed I got:

77
77

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? Can anyone help to explain it please? Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dsafgdafgdf45345 2016-08-29 14:17
    关注

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

    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 allows us a shortcut := that both declares a variable and assigns a value

    a := 77
    

    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.

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

    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.

    For example look at this code

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?