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 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式