Rust If Else
Rust treats if and else as expressions rather than mere statements, which means you can assign the result of a branch directly to a variable without a separate ternary operator.
The Basics of if/else
An if expression in Rust starts with the if keyword, followed by a boolean condition and a block of code in curly braces. Parentheses around the condition are optional and idiomatically omitted, but the curly braces around each branch are mandatory, even when the branch is a single line.
Basic if / else if / else
fn main() {
let temperature = 22;
if temperature > 30 {
println!("It's hot outside!");
} else if temperature > 15 {
println!("Nice weather today.");
} else {
println!("Bring a jacket.");
}
}Conditions Must Be Boolean
Note: Rust performs no implicit truthiness conversion. Writing if number { ... } is a compile error even when number is 0 or 1 — you must write an explicit comparison such as if number != 0 instead.
if as an Expression
Using if as an expression
fn main() {
let age = 20;
let category = if age < 13 {
"child"
} else if age < 20 {
"teenager"
} else {
"adult"
};
println!("You are classified as: {}", category);
}Note: When using if as an expression, leave off the semicolon after the final line of each branch. Adding one turns that branch into a statement that evaluates to (), which will then fail to match the type of the other branches.
if as the final expression in a function
fn classify_number(n: i32) -> &'static str {
if n == 0 {
"zero"
} else if n > 0 {
"positive"
} else {
"negative"
}
}
fn main() {
for n in [-5, 0, 8] {
println!("{} is {}", n, classify_number(n));
}
}- Parentheses around the condition are optional and idiomatically left out.
- Curly braces are required around every branch, even one-liners.
- An if with no else implicitly returns () and can only be used as a statement.
- Every branch of an if used as an expression must resolve to the same type.
Exercise: Rust If Else
What is required when using an if/else block as an expression to produce a value, e.g. `let x = if cond { 1 } else { 2 };`?