dsdtszi0520538 2015-09-25 08:36 采纳率: 100%
浏览 70
已采纳

为什么可以使用for循环两次声明相同的var?

I was trying Go on http://tour.golang.org/, and I saw that it was possible to declarate two times the same var using := in for loop. The output is the same with the Go compiler.

Here is my test : (see the var i, it was declared two times)

package main

import "fmt"

func main() {
    i := "Hello"
    a := 0
    for a < 2 {
        fmt.Println(i)
        i := "World !"
        fmt.Println(i)
        a++
    }       
}

Output :

Hello

World !

Hello

World !

Can someone explain that ?

  • 写回答

2条回答 默认 最新

  • doujiao2443 2015-09-25 09:00
    关注

    The short variable declaration i := ... will overshadow the same variable declared outside of the scope of the for loop block.

    Each "if", "for", and "switch" statement is considered to be in its own implicit block

    You can see more at "Go gotcha #1: variable shadowing within inner scope due to use of := operator"

    It refers to this goNuts discussion.

    A short variable declaration can redeclare the same variable within a block, but since i is also declared outside the for block, it keeps its value outside said block (different scope).

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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?