未定义的变量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>

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