Skip to content
Theory · Conditions and Loops · lesson 1 of 6

The if expression

What you'll learn

What you'll learn:

  • choose which code runs with if, else if and else;
  • get a value out of an if and out of a loop;
  • repeat code with the loop, while and for loops and interrupt them with break and continue;
  • walk the ranges 1..5 and 1..=5 and leave nested loops by a label.
A fork with a signpost: if leads left to a bus stop under a cloud, and else right to the park trees

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:

Rust
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:

  1. let score = 72; puts the number 72 into the variable score.
  2. if score >= 90: the condition is false, so the first branch is skipped.
  3. else if score >= 60: this condition is true, and the program prints passed.
  4. The else branch 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 < b and a > b: less than and greater than;
  • a <= b and a >= 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:

Rust
let score = 72;
let result = if score >= 60 { "passed" } else { "failed" };
println!("{result}"); // passed

Let's take the second line apart:

  1. The condition score >= 60 is true, so the first branch is chosen.
  2. The value of this branch is the text "passed", and it becomes the value of the whole if.
  3. let result = puts this value into the variable result.

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:

Rust
let score = 72;
let result = if score >= 60 { "passed" } else { 0 }; // ✗
TEXT
error[E0308]: `if` and `else` have incompatible types

The 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:

Rust
fn main() {
    let count = 3;
    if count { // ✗
        println!("not zero");
    }
}
TEXT
error[E0308]: mismatched types

The 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 if and else check the conditions from top to bottom and run the first branch whose condition is true.
  • A condition must have type bool: if count with a number does not compile; write if count != 0.
  • if is an expression: let x = if c { a } else { b }; puts the value of the chosen branch into x.
  • All branches of an if give values of one type, and an if without else cannot be a value.