if/else
Branching with if
-else
is similar to that of other languages. The expression does not need to be surrouned by parentheses ( )
but the braces { }
are required.
i := 123;
if i > 100 {
i = 100;
}
fmt.println(i);
An if
statement can have a initial statement to execute before the condition. This is usually an assignment of a variable declaration; variables declared by the statement are only in the scope of the if
statement.
if x := 12; x > 10 {
fmt.println(x);
}
Variables declared by the if
initial statement are also available inside any of the else blocks.
if x := -2; x < 0 {
fmt.println("Negative x,", -x);
} else {
fmt.println("Positive x,", x);
}
if
-else
statements can be chained together.
if x := 12; x == 0 {
fmt.println("Zero");
} else if x < 10 {
fmt.println("Single digits");
} else if x < 20 {
fmt.println("Less than 20");
} else if x < 100 {
fmt.println("Less than 100");
} else {
fmt.println("Numbers go that high?");
}