Sub topic 4
Branching with if/else
This chapter covers if and else in Rust. It assumes you can build and run a program with cargo, know the primitive types (integers, booleans, strings), and understand let and let mut. It builds on the previous chapter's distinction between statements and expressions.
The basic form
An if expression evaluates a condition and runs a block when the condition is true. The condition must have type bool. Parentheses around it are not needed.
fn main() {
let temperature = 31;
if temperature > 30 {
println!("hot");
} else if temperature > 15 {
println!("mild");
} else {
println!("cold");
}
}Branches are tried from top to bottom. The first condition that is true wins, and the rest are skipped. The else branch runs when no condition matched. Braces are required around every branch body, even for a single statement.
The condition must be a bool
Rust does not convert other types to bool. Integers, strings, and Option values are never "truthy" or "falsy". This code does not compile:
fn main() {
let count = 3;
if count {
println!("non-zero");
}
}The compiler reports a mismatched types error: it expected bool and found an integer. Write the comparison you mean instead.
fn main() {
let count = 3;
if count != 0 {
println!("non-zero");
}
}This rule removes a class of bugs common in C, such as writing if (x = 5) when you meant ==. In Rust, if x = 5 fails because an assignment has type (), not bool.
if is an expression
In Rust, if produces a value. The value of the whole if is the value of the branch that ran. That lets you use it on the right side of a let, as a function argument, or as a function's final expression.
fn classify(n: i32) -> &'static str {
if n < 0 {
"negative"
} else if n == 0 {
"zero"
} else {
"positive"
}
}
fn main() {
println!("{}", classify(-4));
}Each branch ends with an expression and no semicolon. The final expression of a block is the block's value. The if is the last expression in classify, so its value is the function's return value.
Rust has no ternary operator (cond ? a : b). You write the same thing with if:
fn main() {
let logged_in = true;
let label = if logged_in { "Sign out" } else { "Sign in" };
println!("{label}");
}Note the semicolon after the closing brace. The let statement ends there, not the if.
Branches must have the same type
Every branch of an if that is used as a value must produce the same type. The compiler checks this at compile time, because a variable can only have one type.
fn main() {
let flag = true;
let value = if flag { 10 } else { "ten" };
println!("{value}");
}This fails with an "if and else have incompatible types" error. If you need to represent two kinds of result, use a common type, such as an enum or a String, or convert one branch.
fn main() {
let flag = false;
let value: String = if flag { 10.to_string() } else { "ten".to_string() };
println!("{value}");
}An if without else
An if with no else has type (), the unit type. That is because when the condition is false, there is no value to produce, so the only type that works for both outcomes is (). As a result, the if body must also evaluate to ().
fn main() {
let n = 5;
let x = if n > 3 { 1 };
println!("{x:?}");
}This does not compile. The compiler says the if may be missing an else clause, because the true branch produces an integer and the implicit false branch produces (). The fix is to add an else with an integer value, or to drop the let and use the if only for its side effects.
The semicolon trap
The most common mistake with if as an expression is a stray semicolon. A semicolon turns an expression into a statement, and a statement has type ().
fn sign(n: i32) -> i32 {
if n < 0 {
-1;
} else {
1;
}
}This fails to compile. Each branch has type () because of the semicolons, but the function promises i32. Remove the semicolons to fix it:
fn sign(n: i32) -> i32 {
if n < 0 {
-1
} else {
1
}
}
fn main() {
println!("{}", sign(-9));
}When you see an error such as "expected i32, found ()" near an if, look for a semicolon after a branch's last line.
Using if as a statement
When you only need side effects, if works as a statement. If the if is in the middle of a block, you do not need a semicolon after it, as long as its type is ().
fn main() {
let mut total = 0;
for n in 1..=10 {
if n % 2 == 0 {
total += n;
}
}
println!("{total}");
}Combining conditions
Use && (and), || (or), and ! (not) to build conditions. && and || short-circuit: the right side is evaluated only when the left side does not already decide the result. This matters when the right side could fail or is expensive.
fn is_valid_index(items: &[i32], i: usize) -> bool {
i < items.len() && items[i] >= 0
}
fn main() {
let data = [4, -1, 7];
println!("{}", is_valid_index(&data, 1));
println!("{}", is_valid_index(&data, 10));
}For index 10, the left side i < items.len() is false, so items[i] never runs and the program does not panic. Swapping the two operands would panic with an index out of bounds error.
Precedence, from highest to lowest, is !, comparison operators, &&, then ||. Add parentheses when mixing && and || so a reader does not have to remember it.
Comparing values of the right type
Both sides of a comparison must have the same type. Rust does not promote an i32 to an i64 automatically for < or ==.
fn main() {
let small: i32 = 5;
let big: i64 = 10;
if i64::from(small) < big {
println!("small is less");
}
}Without the i64::from conversion, this fails with a mismatched types error. The conversion is explicit, and it is lossless, so From is the right tool here. Avoid as when a narrowing conversion could silently change the value.
Choosing between if/else chains and match
A long else if chain that compares one value against several constants is usually clearer as a match, which the compiler checks for completeness. Keep if for conditions that are boolean tests unrelated to each other.
| Situation | Better fit |
|---|---|
| One or two boolean conditions | `if` / `else` |
| Choosing between two values | `if` as an expression |
| Many cases on one value | `match` |
| Conditions on different variables | `else if` chain |
| Checking one pattern of an `Option` or `Result` | `if let` |
A later chapter covers match and if let in detail.
How the compiler sees an if
Control flow in if is a decision made at run time, but the types are fixed at compile time. The following diagram shows the process for let v = if cond { a } else { b };.
Only one block runs. The compiler requires that a and b have the same type so that v has a single type no matter which path ran.
Branches that diverge
A branch can end in return, break, continue, or a panic!. These expressions never produce a value, so they have the type ! (the never type), which fits any expected type. This is why one branch of an if can return early while the other supplies the value.
fn parse_or_zero(s: &str) -> i32 {
let n = if s.is_empty() {
return 0;
} else {
s.len() as i32
};
n * 2
}
fn main() {
println!("{}", parse_or_zero(""));
println!("{}", parse_or_zero("abc"));
}In the first branch, return 0; never gives a value to n, so the compiler accepts it next to a branch that produces an i32. A later chapter covers the never type in more detail.
Common errors
- Non-bool condition. Error: mismatched types, expected
bool. Fix: compare explicitly, for examplex != 0. - Different branch types. Error:
ifandelsehave incompatible types. Fix: make both branches the same type. - Missing
elsewhen a value is needed. Error:ifmay be missing anelseclause. Fix: add anelsethat produces the same type. - Stray semicolon after a branch value. Error: expected a type, found
(). Fix: remove the semicolon. - Mixed integer types in a comparison. Error: mismatched types. Fix: convert one side with
Fromortry_from.
Exercises
Exercise
Why does let x = if n > 3 { 1 }; fail to compile, and how would you fix it so x is an i32?
Show answer
An if without else has type (). The true branch produces an integer, so the types differ. Add an else branch that produces an i32, for example let x = if n > 3 { 1 } else { 0 };.
Exercise
What does this function return for n = 0, and why does it compile? fn f(n: i32) -> i32 { if n > 0 { 1 } else if n < 0 { -1 } else { 0 } }
Show answer
It returns 0. It compiles because the if chain ends in an else, every branch is an i32 expression with no semicolon, and the if is the function's final expression, so its value is returned.
Exercise
In i < items.len() && items[i] >= 0, what happens if i is 10 and the slice has 3 elements, and what would happen if the operands were swapped?
Show answer
The left side is false, so && short-circuits and items[i] is never evaluated. With the operands swapped, items[10] runs first and the program panics with an index out of bounds error.