Control flow
Conditions must be booleans, the first true branch wins, and if is an expression that produces a value.
- Write if / else if / else chains with boolean conditions
- Predict which branch runs when several conditions are true
- Use if as an expression on the right-hand side of let
let test = 6;
if test % 4 == 0 {
println!("Test is divisible by 4!");
} else if test % 3 == 0 {
println!("Test is divisible by 3!");
} else if test % 2 == 0 {
println!("Test is divisible by 2!");
} else {
println!("Test is not divisible by 4,3,2!");
}
There are no parentheses around the condition, and the braces are mandatory. The condition must be a bool: unlike C, Rust never treats a number as true or false, so if test { ... } is a type error, not a test for non-zero.
The first true branch wins
The conditions are checked from the top, and the first one that holds is the only one that runs. For test = 6, 6 % 4 is 2, so the first test fails, and 6 % 3 is 0 — “divisible by 3” prints, even though 6 is divisible by 2 as well.
The order of the arms is therefore part of the logic. Here it goes from the most specific test to the least, which is usually what you want. When a chain grows long, a match expression on the value is often clearer, and the compiler then checks that every case is covered.
if is an expression
let condition = true;
let number = if condition { 5 } else { 6 };
In Rust, if produces a value: the value of the last expression in whichever block runs. That replaces C’s ternary operator ?: with ordinary syntax. Because number must have one type, both branches must produce the same type — if condition { 5 } else { "six" } is rejected at compile time.
Try it yourself. Rewrite the divisibility chain as a single let message = if ... { ... } else { ... }; followed by one println!. Then write it again with match (test % 4, test % 3, test % 2) and tuple patterns such as (0, _, _).