未定义的变量 golang

有人能告诉我为什么 num 是未定义的吗 :: 这是 go playground 链接你也可以在这里查看这段代码: https: //play.golang.org/p/zR9tuVTJmx-

package main

import "fmt"

func main() {

    if 7%2 == 0 {

        num := "first"

    } else {

        num := "second"

    }

    fmt.Println(num)


  }


波斯汪
浏览 97回答 1
1回答

白板的微信

那是与词法作用域相关的东西,在这里查看介绍基本上,花括号内的任何变量都{}被视为该块内的新变量。所以在上面的程序中你创建了两个新变量。块类似于围绕一个变量。如果您在街区外,则看不到它。你需要在街区内才能看到它。package mainimport "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 mainimport "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)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go