7

4 basic if-else statement patterns

 3 years ago
source link: https://yourbasic.org/golang/if-else-statement/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

4 basic if-else statement patterns

yourbasic.org/golang
fork-in-road.jpg

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.

  • If the expression evaluates to true, the if branch is executed,
  • otherwise, if present, the else branch is executed.

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

invisible-man.jpg

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:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK