Undefind Variable issue

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

  }

The if and else blocks define new scopes. The num variable is created inside one of these blocks and thus is not visible outside.

what can I use here, if I have this kind of query

In order to properly print num, you would have to declare it outside of the if-else blocks. Here’s one solution.

package main

import (
	"fmt"
)

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

Considering going through the Tour of the Go programming language if you haven’t already, then read this article on Scopes in Go.

5 Likes