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条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了