Golang: if then else

By Xah Lee. Date: . Last updated: .

If

package main

import "fmt"

func ff(x int) string {
        if x < 0 {
                return "no"
        }
        return "yes"
}

func main() {
        fmt.Println(ff(-1), ff(2))
}

// no yes

note, there's no parenthesis after the “if”.

If else

package main

import "fmt"

func ff(x int) string {

        if x < 0 {
                return "no"
        } else {
                return "yes"
        }

}

func main() {
        fmt.Println(ff(-1), ff(2))
}

// no yes

If else if else

package main

import "fmt"

func ff(x int) int {

        if x < 0 {
                return -1
        } else if x > 0 {
                return 1
        } else {
                return 0
        }

}

func main() {
        fmt.Println(ff(-2), ff(2), ff(0))
}

// -1 1 0

If with a short statement

the if statement can start with a short statement to execute before the condition.

Variables declared by the statement are in scope of the if block and and all the else blocks.

package main

import "fmt"

func ff(x int) string {

        // if statement can start with a short statement, e.g. var declaration
        if i := -2; x < i {
                return "no"
        }
        return "yes"
}

func main() {
        fmt.Println(ff(-1), ff(2))
}

// yes yes

ternary if, if expression

there's no if expression, such as JavaScript's ( test ? expr1 : expr2 )

Reference

The Go Programming Language Specification - The Go Programming Language#If_statements