Go if...else

Go if/else statement

Let's write some code that can use if/else condition in golang.

if condition

Problem Statement: Ask user to enter his name then print welcome if user's name is anji.

package main
import "fmt"

func main(){
    var name string
    fmt.Println("Enter your name")
    fmt.Scanln(&name)
    if name == "anji" {
        fmt.Println("Welcome")
    }
}

if/else condition

Problem Statement: Ask user to enter his name then print welcome if user's name is anji otherwise print invalid name

package main
import "fmt"

func main(){
    var name string
    fmt.Println("Enter your name")
    fmt.Scanln(&name)
    if name == "anji" {
        fmt.Println("Welcome")
    }else{
        fmt.Println("invalid name")
    }
}

if/else if/else condition

Problem Statement: Ask user to enter a number and find if the number is postive, zero or negative.

package main
import "fmt"

func main(){
    var number int8
    fmt.Println("Enter number")
    fmt.Scanln(&number)
    if num == 0 {
        fmt.Println("zero")
    }else if num > 0{
        fmt.Println("positive")
    }else{
        fmt.Println("negative")
    }
}

Nested if/else conditions

We can use if/else conditions inside if/else condition, this is called nested conditions. I don't think we need an example code for this.

if/else with init statement

Let's modify the above user welcome program

package main
import "fmt"

func getName() string{
    return "anji"
}

func main(){
    if name := getName(); name == "anji" {
        fmt.Println("Welcome")
    }else{
        fmt.Println("invalid name")
    }
}

In above program we have initialized the name within the if statement and using that in the comparison. This is useful when we don't want the data of the variable after the if condition to save the memory.