-1

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)

  }
Archana Sharma
  • 1,953
  • 6
  • 33
  • 65
  • 1
    You have three different num variables: Two declared in each if/else block (unused) and one in the last line (used but undeclared). Take the Tour of Go which explains what := does and how to use it. – Volker Aug 23 '18 at 05:30

1 Answers1

2

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)
}
nilsocket
  • 1,441
  • 9
  • 17