4 basic if-else statement patterns

yourbasic.org/golang

Basic syntax

if x > max {
    x = max
}
if x <= y {
    min = x
} else {
    min = y
}

An if statement executes one of two branches according to a boolean expression.

With init statement

if x := f(); x <= y {
    return x
}

The expression may be preceded by a simple statement, which executes before the expression is evaluated. The scope of x is limited to the if statement.

Nested if statements

if x := f(); x < y {
    return x
} else if x > z {
    return z
} else {
    return y
}

Complicated conditionals are often best expressed in Go with a switch statement. See 5 switch statement patterns for details.

Ternary ? operator alternatives

You can’t write a short one-line conditional in Go; there is no ternary conditional operator. Instead of

res = expr ? x : y

you write

if expr {
    res = x
} else {
    res = y
}

In some cases, you may want to create a dedicated function.

func Min(x, y int) int {
    if x <= y {
        return x
    }
    return y
}

Share this page: