dongya2029 2018-08-23 05:07
浏览 32
已采纳

未定义的变量golang [重复]

This question already has an answer here:

Can someone tell me why num is undefined :: Here is go playground link also you can check this code here: https://play.golang.org/p/zR9tuVTJmx-

package main
import "fmt"
func main() {
    if 7%2 == 0 {
        num := "first"
    } else {
        num := "second"
    }
    fmt.Println(num)

  }
</div>
  • 写回答

1条回答 默认 最新

  • doutang6819 2018-08-23 05:47
    关注

    That's something related to lexical scoping, look over here for an introduction

    Basically any variable within {}curly braces is considered as new variable, within that block.

    so In the above program you have created two new variables.

    Block is something like enclosing a around a variable.

    If you are outside a block, you cannot see it. you need to be inside the block in order to see it.

    package main
    
    import "fmt"
    
    func main() {
        if 7%2 == 0 {
            // you are declaring a new variable,
            num := "first"
            //this variable is not visible beyond this point
        } else {
            //you are declaring a new variable,
            num := "second"
            //this variable is not visible beyond this point
        }
        // you are trying to access a variable, which is declared in someother block,
        // which is not valid, so undefined.
        fmt.Println(num)
    
    }
    

    What you are looking for is this:

    package main
    
    import "fmt"
    
    func main() {
        num := ""
        if 7%2 == 0 {
            //num is accessible in any other blocks below it
            num = "first"
        } else {
            num = "second"
        }
        //num is accessible here as well, because we are within the main block
        fmt.Println(num)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据