Sub topic 4
Branching with if/else
This chapter assumes you can build and run a program with cargo. It also assumes you know Rust's primitive types, let and let mut, and the difference between a statement and an expression from the previous chapter.
if produces a value
In Rust, if is an expression. Each branch is a block, and the last expression in the block, written without a semicolon, becomes the value of the whole if. That is why Rust has no ternary operator.
fn classify(n: i32) -> &'static str {
if n < 0 {
"negative"
} else if n == 0 {
"zero"
} else {
"positive"
}
}
fn main() {
println!("{}", classify(-4));
}The if chain is the last expression in classify, so its value is the function's return value. No return keyword is needed.
You can also bind the result directly to a variable:
fn main() {
let n = 7;
let parity = if n % 2 == 0 { "even" } else { "odd" };
println!("{n} is {parity}");
}Here the ; after the closing brace ends the let statement. The semicolons inside the branches would change the result, as the next sections show.
The condition must be a bool
Rust does not convert other types to booleans. if count { ... } with an integer count does not compile. Write the comparison out:
fn main() {
let items: Vec<i32> = Vec::new();
if !items.is_empty() {
println!("has items");
} else {
println!("empty");
}
}Parentheses around the condition are not needed. The compiler warns about unnecessary ones. Braces around each branch are required, even for a single statement.
Every branch must have the same type
The compiler must know the type of the whole if at compile time. If one branch gives a &str and another gives an integer, you get a "if and else have incompatible types" error. Fix it by making the branches agree, for example by converting both to String.
The same rule explains a frequent mistake. Adding a semicolon to the last line of a branch turns that line into a statement. The block then evaluates to (), the unit type, and the compiler reports a mismatch against the other branch or the function's return type.
if without else
An if with no else has type (). That means its block must also evaluate to ().
fn main() {
let temperature = 31;
if temperature > 30 {
println!("hot");
}
}If you need a value, you must supply an else. Otherwise there is no value to produce when the condition is false.
How the pieces fit
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| "expected `bool`, found integer" | A non-boolean used as the condition | Compare explicitly, such as `n != 0` |
| "`if` and `else` have incompatible types" | Branches return different types | Make both branches the same type |
| "expected `i32`, found `()`" | Stray semicolon after the last expression in a branch | Remove the semicolon |
| "`if` may be missing an `else` clause" | `if` used for a value with no `else` | Add an `else` branch |
Exercise
What does let x = if true { 5 } else { "five" }; do, and why?
Show answer
It does not compile. The two branches have different types (an integer and a &str), and an if expression must have a single type known at compile time.
Exercise
The function fn sign(n: i32) -> i32 { if n < 0 { -1; } else { 1 } } fails to compile. Why, and how do you fix it?
Show answer
The semicolon after -1 makes the first branch a statement, so that block has type () instead of i32. Remove the semicolon so the branch returns -1.