if/else Expressions
if and else let your program pick a different path depending on whether something is true or false.Basic if/else
An if expression evaluates a boolean condition and runs the associated block only when it is true; an optional else block runs otherwise. No parentheses are needed around the condition, unlike C or Java.
Example: Basic if/else
fn main() {
let number = 7;
if number > 5 {
println!("Greater than five");
} else {
println!("Five or less");
}
}
Login to try C/C++/Java/PHP code in the editor
else if Chains
Multiple conditions can be chained with else if, checked in order from top to bottom. The first matching branch runs, and the rest are skipped.
Example: else if Chains
fn main() {
let grade = 85;
if grade >= 90 {
println!("A");
} else if grade >= 80 {
println!("B");
} else {
println!("C or below");
}
}
Login to try C/C++/Java/PHP code in the editor
if as an Expression
Because if is an expression, not just a statement, it can produce a value directly, which you can assign to a variable. Both branches must return values of the same type.
Note: Notice there are no semicolons after 5 and 6 -- they are the tail expressions of each block.
Example: if as an Expression
fn main() {
let condition = true;
let number = if condition { 5 } else { 6 };
println!("number is {}", number);
}
Login to try C/C++/Java/PHP code in the editor
Condition Must Be a Bool
Rust requires the if condition to be an actual bool value; it will not implicitly treat a nonzero integer as true, unlike C. This prevents an entire category of bugs from mistyped conditions.
Example: Condition Must Be a Bool
fn main() {
let count = 3;
if count != 0 {
println!("count is non-zero: {}", count);
}
}
Login to try C/C++/Java/PHP code in the editor
- Wrapping the condition in parentheses like
if (x > 5), which is unnecessary and unidiomatic in Rust. - Forgetting that
ifis an expression and can return a value, then writing overly verbose code with extralet mutvariables. - Mixing types between the
ifandelsebranches when usingifas an expression, which fails to compile.
if/else if/elsebranch on boolean conditions; no parentheses are required around the condition.ifis an expression in Rust, so it can produce a value that is assigned directly to a variable.- All branches of an
ifused as an expression must evaluate to the same type. - The condition must be a
bool-- Rust does not implicitly convert numbers to booleans.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: