Go - Control flows - If/else

Source: Use control flows in Go

Syntax

  • The else clause is optional, but the if braces are still required
  • Go doesn’t offert support for ternary if statements
if x%2 == 0 {
    fmt.Println(x, "is even")
}

If we want to add the else clause:

if x%2 == 0 {
    fmt.Println(x, "is even")
} else {
    fmt.Println(x, "is odd")
}

Compound if statements

func givemeanumber() int {
    return -1
}

func main() {
    if num := givemeanumber(); num < 0 {
        fmt.Println(num, "is negative")
    } else if num < 10 {
        fmt.Println(num, "has only one digit")
    } else {
        fmt.Println(num, "has multiple digits")
    }
}

The num variable stores the value returned by the givemeanumber() function, and the variable is available in all if branches. The value of num is only available inside the if statement.