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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器