If Expressions
An if expression conditionally executes one of two branches based on a boolean condition.
if_expr = "if" expression "{" block "}" [ else_clause ] ;
else_clause = "else" ( "{" block "}" | if_expr ) ;
The condition expression MUST have type bool.
If an else branch is present, both branches MUST have the same type. The type of the if expression is the type of its branches.
If no else branch is present, the then branch MUST have type ().
fn main() -> i32 {
let x = if true { 42 } else { 0 };
x
}
If the condition evaluates to true, the then-branch is evaluated and the if expression evaluates to the then-branch's value; otherwise the else-branch (if present) is evaluated and the if expression evaluates to its value. When no else-branch is present, the if expression evaluates to ().
fn main() -> i32 {
let n = 5;
if n > 3 { 100 } else { 0 }
}
If expressions can be chained using else if:
fn main() -> i32 {
let x = 5;
if x < 3 { 1 }
else if x < 7 { 2 }
else { 3 }
}