未定义的变量golang

时间:2018-08-23 05:07:11

标签: go

有人可以告诉我为什么num是未定义的吗::这是去操场的链接,您也可以在这里检查以下代码: https://play.golang.org/p/zR9tuVTJmx-

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

  }

1 个答案:

答案 0 :(得分:2)

这与词法作用域有关,请在此处查看introduction

{}大括号内的任何变量基本上都被视为该块内的新变量。

所以在上面的程序中,您创建了两个新变量。

Block类似于将一个变量括起来。

如果您位于街区之外,则看不到它。您需要先进入街区才能看到它。

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)

}

您正在寻找的是这个

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