The if expression
What you'll learn:
- choose which code runs with
if,else ifandelse; - get a value out of an
ifand out of aloop; - repeat code with the
loop,whileandforloops and interrupt them withbreakandcontinue; - walk the ranges
1..5and1..=5and leave nested loops by a label.

Picture a fork in the road with a signpost. It reads: if it's raining, turn left to the bus stop; otherwise, go right through the park. You read the condition and take one road, and this time you don't walk the other. A program needs forks like this too: print one thing or another, calculate one way or another.
So far the instructions in main all ran in a row, from top to bottom. The if construct runs the block in curly braces only when the condition after if is true. The block after else runs when the condition is false:
fn main() {
let score = 72;
if score >= 90 {
println!("excellent");
} else if score >= 60 {
println!("passed"); // passed
} else {
println!("failed");
}
}Let's go through the program line by line:
let score = 72;puts the number72into the variablescore.if score >= 90: the condition is false, so the first branch is skipped.else if score >= 60: this condition is true, and the program printspassed.- The
elsebranch is skipped: the fork is already behind us.
Three kinds of branches
Each block in curly braces is called a branch. The example has three, and each has its own role.
if
The if branch opens the fork. It has three parts:
- the keyword
if; - a condition, such as
score >= 90; - a block in curly braces that runs when the condition is true.
Curly braces are required, even when the branch holds one instruction. Parentheses around the condition are not needed: with them the program builds, but the compiler warns about unnecessary parentheses.
else if
An else if branch adds one more condition to the fork. It is checked only when every condition above it was false.
The chain checks the conditions from top to bottom, runs the first branch whose condition is true and skips the rest. That is why the second branch needs no score < 90 check: it is reached only when the first condition is already false.
Here the fork differs from a real road. A traveler may pick the signpost that fits best, while Rust reads the signposts strictly from top to bottom and turns at the first one that fits.
else
The else branch has no condition. It runs when every condition above it is false, and it always comes last. Without it, no branch runs in that case.
A condition of type bool
A condition is a value of type bool, that is, true or false. Comparisons produce such values:
a < banda > b: less than and greater than;a <= banda >= b: less than or equal, greater than or equal;a == b: equal;a != b: not equal.
With score equal to 72, the comparison score >= 90 gives false, and score >= 60 gives true. Note that "equal" in a comparison is written with two signs, ==, while a single = puts a value into a variable.
if returns a value
In Rust, if is an expression, that is, code that evaluates to a value. The value of an if is what stands in the chosen branch. So you can put the result of an if straight into a variable:
let score = 72;
let result = if score >= 60 { "passed" } else { "failed" };
println!("{result}"); // passedLet's take the second line apart:
- The condition
score >= 60is true, so the first branch is chosen. - The value of this branch is the text
"passed", and it becomes the value of the wholeif. let result =puts this value into the variableresult.
Inside the branches there is no semicolon after the value. The semicolon after the last } ends the let instruction, as in any other line with let.
Many languages have a ternary operator condition ? a : b for this kind of choice. Interviewers like to ask why Rust has none. The answer: it isn't needed, because if itself returns a value.
Branches of one type
The compiler knows the type of every variable while it builds the program. So all branches of an if must give values of one type:
let score = 72;
let result = if score >= 60 { "passed" } else { 0 }; // ✗error[E0308]: `if` and `else` have incompatible typesThe first branch gives text, the second gives a number, and the compiler cannot pick a type for result. For the same reason an if without else cannot be a value: when the condition is false, there is nothing to give.
Common mistake
A number is written instead of a condition, as is customary in C or Python:
fn main() {
let count = 3;
if count { // ✗
println!("not zero");
}
}error[E0308]: mismatched typesThe program does not compile: the compiler expects a bool in the condition but finds an integer. In C and Python a non-zero number counts as true, but Rust has no such "truthiness", and no other type turns into a bool on its own.
This is a build error, not a panic while the program runs. The program never starts, so no branch runs, not even else if there is one. The comparison is written out: if count != 0.
Key points
if,else ifandelsecheck the conditions from top to bottom and run the first branch whose condition is true.- A condition must have type
bool:if countwith a number does not compile; writeif count != 0. ifis an expression:let x = if c { a } else { b };puts the value of the chosen branch intox.- All branches of an
ifgive values of one type, and anifwithoutelsecannot be a value.