Go Conditinals - if else statement

if Statement

Simple if syntax

The if statement looks as it does in C or Java, except that the ( ) are gone and the { } are required. Like for, the if statement can start with a short statement to execute before the condition. Variables declared by the statement are only in scope until the end of the if. Variables declared inside an if short statement are also available inside any of the else blocks.

if answer != 42 {
    return "Wrong answer"
}

Read more - If statement example

If with short statement

if err := foo(); err != nil {
    panic(err)
}

See more - If with a short statement

if-else statement

Here’s an example of using if and else

package main

import (
    "fmt"
)

func main() {
    x := 42

    if x == 40 {
        fmt.Println("Our value was 40")
    } else {
        fmt.Println("Our value was not 40")
    }
}

playground

We can also use else if as many times as we want within the if statement.

package main

import (
    "fmt"
)

func main() {
    x := 42
    if x == 40 {
        fmt.Println("Our value was 40")
    } else if x == 41 {
        fmt.Println("Our value was 41")
    } else if x == 42 {
        fmt.Println("Our value was 42")
    } else if x == 43 {
        fmt.Println("Our value was 43")
    } else {
        fmt.Println("Our value was not 40")
    }
}

playground

http://www.golangbootcamp.com/book/control_flow

https://github.com/vprf06/GoProgramming/blob/5519dbb87bc53b497b278cb149f55c718e50a273/section_06/6.08.md