CourseLesson 4 · Conditions, Matching and LoopsSolve

Lesson 04

Conditions, Matching and Loops

Goal

By the end of this lesson you will be able to:

  1. Write a condition that produces a real bool.

  2. Branch on a condition with if, else and else if.

  3. Use if as an expression that produces a value.

  4. Use match to pick one answer out of many, with patterns, ranges, guards and bindings.

  5. Choose between if and match for a given problem.

  6. Repeat a block of code with loop, and stop it with break.

  7. Repeat a block of code while a condition holds, with while.

  8. Write a range with a..b and a..=b.

  9. Step through a range or an array with for.

  10. Get both the index and the value of an array element with .enumerate().

Conditions

A condition is an expression that a program tests before deciding what to do next. In Rust, a condition must produce a bool: the value true or the value false, and nothing else.

Conditions Must Be bool

In C, a condition can be any number. Zero counts as false and every other value counts as true, so this compiles and prints the message:

int count = 5;

if (count) {
    printf("there is something\n");
}

Rust does not do this. A condition has to be a bool and nothing else. The same code in Rust is a compile error:

let count: i32 = 5;

if count {                  // error: expected `bool`, found `i32`
    println!("there is something");
}
error[E0308]: mismatched types
 --> src/main.rs:4:8
  |
4 |     if count {
  |        ^^^^^ expected `bool`, found `i32`

Making a bool out of a Number

You write the test you actually mean. The comparison operators ==, !=, <, <=, > and >= all give back a bool:

What you meanIn CIn Rust
the count is not zeroif (count)if count != 0
the count is zeroif (!count)if count == 0
the number is evenif (n % 2 == 0)if n % 2 == 0

You can also store the answer, because a comparison is just a value:

let count: i32 = 5;
let has_items: bool = count != 0;   // has_items is true

if has_items {
    println!("there is something");
}

Say the Test Out Loud

Rust makes you write the comparison instead of letting the number stand in for it. The line then says what it checks. count != 0 cannot be misread; if (count) can.

if and else

The Shape of an if

An if runs a block only when its condition is true. There are no parentheses around the condition, but the braces around the block are always required, even for one line:

let age: u32 = 20;

if age >= 18 {
    println!("can vote");
}
can vote

Nothing happens if the condition is false. The block is simply skipped.

else and else if

else runs its block when the condition is false. else if adds another condition to check when the ones above it were all false:

let score: i32 = 72;

if score >= 80 {
    println!("distinction");
} else if score >= 65 {
    println!("merit");
} else if score >= 50 {
    println!("pass");
} else {
    println!("fail");
}
merit

The conditions are tried from top to bottom. The first one that is true runs its block, and every condition after it is skipped, even if it would also have been true. score is 72, so score >= 80 fails, score >= 65 succeeds, and score >= 50 is never even tested.

Blocks and Their Value

A block is the code between a pair of braces, { }. A block produces a value: the value of its last line, as long as that last line has no semicolon. A line with a semicolon is a statement. It runs and produces nothing. A line without one, at the end of a block, is an expression. It runs and hands its value out of the block.

let x = {
    let a = 3;
    let b = 4;
    a + b            // no semicolon: this is the block's value
};

println!("{x}");
7

a and b are declared with statements, each ending in a semicolon. a + b has no semicolon, so it is the value the whole block produces, and that value is what x is set to.

if as an Expression

An if is built from blocks, so an if is itself an expression. It can be the right-hand side of a let, as long as it has an else:

let score: i32 = 72;

let grade = if score >= 50 {
    "pass"
} else {
    "fail"
};

println!("{grade}");
pass

Read it the same way as the block example above. "pass" and "fail" have no semicolon, so each is the value of the branch it sits in. Whichever branch runs, its value becomes the value of the whole if, and that value is what grade is set to. Note the semicolon after the closing brace of the else block: the whole if is the right side of a let, so the statement ends there.

Both Branches Must Have the Same Type

Every branch of an if used as an expression must produce the same type. The compiler has to know the type of grade before the program runs, and it cannot know that if the branches disagree:

let grade = if score >= 50 {
    "pass"
} else {
    0                // error: expected `&str`, found integer
};
error[E0308]: `if` and `else` have incompatible types
 --> src/main.rs:4:9
  |
4 |     0
  |     ^ expected `&str`, found integer

An if With No else Has No Value

An if with no else is only ever used as a statement, never as an expression. If its condition is false, there is no branch left to produce a value, so Rust does not let you assign it to anything.

Pattern Matching with match

A chain of if and else if answers one yes-or-no question at a time. When a value has several possible shapes, that chain gets long and it is easy to forget one case. match is built for this. It compares one value against a list of patterns, from top to bottom, and runs the first arm that fits.

The Shape of a match

match n {
    0 => println!("zero"),
    1 => println!("one"),
    _ => println!("something else"),
}

Read it line by line:

  • match n names the value being examined.

  • Each line inside the braces is an arm. An arm is a pattern, then =>, then what to do.

  • The arms are tried in order. The first one that fits wins, and the rest are skipped.

  • _ is the catch-all pattern. It fits any value.

  • Arms are separated by commas.

Every Case Must Be Covered

A match has to handle every value the type can hold. If it does not, the program does not compile. This is why _ is there in the example above. A whole number has millions of possible values, and two arms cannot cover them all, so a catch-all arm is needed.

match flag {
    true  => println!("on"),
    false => println!("off"),
}

This one needs no _. A bool has exactly two values, and both have an arm, so the match is complete.

The Compiler Counts the Cases for You

Forgetting a case is one of the most common bugs in programming. Rust turns it into a compile error. If you add a new case to your data later, every match that does not handle it stops compiling, and the compiler tells you where to go.

match Produces a Value

A match is an expression, so it can be assigned. Every arm must produce the same type:

let name = match bit {
    0 => "off",
    1 => "on",
    _ => "not a single bit",
};

Note the semicolon after the closing brace. The whole match is the right side of a let, so the statement ends there.

Several Values in One Arm

| inside a pattern means “or”. It is not the bitwise OR operator here; in a pattern it just lists alternatives:

match digit {
    1 | 3 | 5 | 7 | 9 => println!("odd digit"),
    0 | 2 | 4 | 6 | 8 => println!("even digit"),
    _ => println!("not a digit"),
}

Ranges in a Pattern

a..=b matches every value from a to b, including both ends:

match score {
    0..=49   => "fail",
    50..=64  => "pass",
    65..=79  => "merit",
    80..=100 => "distinction",
    _        => "out of range",
}

Guards

A guard is an if attached to an arm. The arm fits only when the pattern matches and the guard is true. The guard is a normal condition, so it must give a bool:

match n {
    0 => println!("zero"),
    n if n % 2 == 0 => println!("even"),
    _ => println!("odd"),
}

Order still decides the answer. 0 is even, but the 0 arm is written first, so zero never reaches the guard.

Binding the Matched Value

A plain name in a pattern matches anything and gives that value a name inside the arm. To match a range and keep the value, join them with @:

match code {
    c @ 1..=9 => println!("single digit: {c}"),
    c         => println!("something else: {c}"),
}

The second arm is a catch-all as well. A bare name fits every value, exactly like _, but it also names it. Use _ when you do not need the value.

Matching Two Values at Once

Put the values in a tuple and match the pair. This is the truth table for AND written as code:

match (a, b) {
    (true,  true)  => println!("both"),
    (true,  false) => println!("only a"),
    (false, true)  => println!("only b"),
    (false, false) => println!("neither"),
}

All four rows are present, so no _ is needed. Inside a tuple pattern you can use _ for a position you do not care about:

match (a, b) {
    (true, _) => println!("a is true, b does not matter"),
    (_, true) => println!("a is false and b is true"),
    _         => println!("neither"),
}

if let — One Pattern Only

When you care about a single pattern and want to ignore everything else, if let says so in one line:

if let 0 = count {
    println!("nothing left");
}

This runs the block only when count is 0. It is a shorter way to write a match whose other arm does nothing.

Choosing Between if and match

Use if for one yes-or-no question, or a short chain of them. Use match when a value has several possible shapes and each one needs its own answer. match keeps the cases side by side, in one place, and the compiler checks that none is missing. Use if let when only one shape matters and every other case should do nothing.

Same Question, Three Answers

if age >= 18 asks one question. match score { 0..=49 => ..., ... } sorts a value into one of several bands. if let 0 = count checks for one exact shape and ignores the rest. Pick the one that says what you mean, not the one that happens to compile.

Repetition with loop

loop runs a block over and over, forever, until something inside it stops the loop. It is the plainest of the three ways Rust repeats work.

loop and break

break leaves the loop immediately. Without it, loop never ends:

let mut count: i32 = 0;

loop {
    println!("{count}");
    count += 1;
    if count == 3 {
        break;
    }
}
0
1
2

count += 1 adds 1 to count and stores the result back in count. The loop runs its block, checks the condition, and stops as soon as count reaches 3.

continue

continue skips the rest of the current pass through the block and jumps straight back to the top of the loop, for the next pass:

let mut n: i32 = 0;

loop {
    n += 1;
    if n > 5 {
        break;
    }
    if n % 2 == 0 {
        continue;
    }
    println!("{n}");
}
1
3
5

Every time n is even, continue skips the println! for that pass. The even numbers are never printed, but the loop keeps counting.

break with a Value

A loop is an expression. break can hand back a value, and that value becomes the value of the whole loop:

let mut count: i32 = 0;

let result = loop {
    count += 1;
    if count == 10 {
        break count * 2;
    }
};

println!("{result}");
20

This is the only one of the three loop forms that can produce a value this way. while and for cannot, because they may finish without ever running break.

Labels and break 'outer

A loop inside another loop is a nested loop. A plain break stops only the innermost one. To stop an outer loop from inside an inner one, give the outer loop a label: a name starting with a single quote, written before the loop, and name that label on the break:

'outer: loop {
    let mut inner_count: i32 = 0;
    loop {
        inner_count += 1;
        if inner_count == 2 {
            break 'outer;
        }
    }
}
println!("done");
done

Without the label, break on its own would only leave the inner loop, and the outer one would run forever. break 'outer; names the loop it means to stop.

while

The Shape of a while

while runs its block only while a condition stays true. It checks the condition before every pass, including the first one:

let mut count: i32 = 0;

while count < 3 {
    println!("{count}");
    count += 1;
}
0
1
2

As soon as count < 3 is false, the loop stops. If the condition is already false the first time it is checked, the block never runs at all.

while against loop with a break

Every while loop can be written as a loop with an if and a break:

let mut count: i32 = 0;

loop {
    if !(count < 3) {
        break;
    }
    println!("{count}");
    count += 1;
}

Both loops print the same three lines. while says the same thing in fewer words, and the stopping condition sits at the top where you read it first. Use while whenever the loop has one condition that decides whether it keeps going. Use loop when the loop should stop for a reason that only shows up partway through the block, such as finding what you were searching for.

Ranges

a..b and a..=b

A range is a value that stands for every whole number between two ends. Rust writes two kinds:

a..bevery number from a up to b, not including b
a..=bevery number from a up to b, including b

0..5 stands for 0, 1, 2, 3, 4. 0..=5 stands for 0, 1, 2, 3, 4, 5. The = sign is the only difference, and it is easy to miss, so read it carefully every time you see a range.

The Same Ranges in a match Pattern

A range written this way is also a valid pattern. The match on score you saw earlier used exactly this form:

match score {
    0..=49   => "fail",
    50..=64  => "pass",
    65..=79  => "merit",
    80..=100 => "distinction",
    _        => "out of range",
}

The pattern 0..=49 fits any value from 0 to 49, including 49. It is the same range you would write in a loop, used to sort a value into a band instead of to step through it.

for

for over a Range

for steps through every value a range stands for, running the block once per value, with that value bound to a name you choose:

for n in 0..5 {
    println!("{n}");
}
0
1
2
3
4

n takes each value from the range in turn, from first to last, and the loop stops on its own once the range is used up. There is no counter to declare and no condition to check.

for over an Array

An array is a fixed-length list of values of the same type, written between square brackets:

let scores = [72, 45, 90, 61, 38];

for score in scores {
    println!("{score}");
}
72
45
90
61
38

for score in scores steps through the array from the first element to the last, binding each one to score in turn.

for x in items against for x in &items

for score in scores hands the array itself to the loop. For an array of numbers that is harmless: the loop receives a copy of the array, and scores is still usable below the loop. For a list whose values are text, or a list that can grow while the program runs, the loop takes the list itself, and the variable cannot be used again afterwards.

Writing &scores instead loops over a reference to the array: a way of looking at the array’s values without taking the array itself, so the list is still there afterwards, whatever it holds:

let scores = [72, 45, 90, 61, 38];

for score in &scores {
    println!("{score}");
}

println!("still have {} scores", scores.len());
72
45
90
61
38
still have 5 scores

When in Doubt, Loop Over a Reference

Looping over &items instead of items works for every kind of list, and leaves the list usable after the loop. It costs one character to write. Make it the form you write by default.

Index and Value with .enumerate()

Sometimes you need to know where a value is in the array, not just what it is. .enumerate() pairs every value with its position, starting the count at 0:

let scores = [72, 45, 90, 61, 38];

for (index, score) in scores.iter().enumerate() {
    println!("position {index}: {score}");
}
position 0: 72
position 1: 45
position 2: 90
position 3: 61
position 4: 38

.iter() gives a reference to each value, one at a time, the same as looping over &scores. .enumerate() wraps that with the position. (index, score) unpacks the pair into two names in one step, so both are ready to use inside the block.

for against while with a Counter

Compare the same loop written both ways. First, while with a counter you manage by hand:

let scores = [72, 45, 90, 61, 38];
let mut i = 0;

while i < scores.len() {
    println!("{}", scores[i]);
    i += 1;
}

Now the same loop with for:

let scores = [72, 45, 90, 61, 38];

for score in &scores {
    println!("{score}");
}

Both print the same five lines. The while version needs a counter declared before the loop, a comparison to check on every pass, and a line to move the counter forward, and it is easy to get any one of those three wrong. The for version has none of that: there is no counter to forget to move, and no chance of stopping one step too early or too late.

Everything Together

This program uses all of the lesson. It reads a fixed list of temperature readings, sorts each one into a band with a match on a range, counts how many readings fall in each band, and prints a summary.

fn main() {
    let readings = [4, 31, 15, -2, 22, 40, 18, 9];

    let mut cold = 0;
    let mut mild = 0;
    let mut hot = 0;

    for degrees in &readings {
        let band = match degrees {
            ..=9    => "cold",
            10..=24 => "mild",
            25..    => "hot",
        };

        match band {
            "cold" => cold += 1,
            "mild" => mild += 1,
            "hot"  => hot += 1,
            _      => {}
        }

        println!("{degrees} is {band}");
    }

    println!("cold: {cold}, mild: {mild}, hot: {hot}");
}
4 is cold
31 is hot
15 is mild
-2 is cold
22 is mild
40 is hot
18 is mild
9 is cold
cold: 3, mild: 3, hot: 2

Three parts of this program need extra explanation.

  • ..=9 and 25.. are ranges with one end left open. ..=9 matches every value up to and including 9. 25.. matches every value from 25 upward. Together with 10..=24 they cover every possible degrees, so the first match needs no _.

  • for degrees in &readings loops over a reference to the array, so readings is still usable for the rest of main. degrees is bound once per element.

  • The second match still needs a _ arm, even though band only ever holds "cold", "mild" or "hot". Text is not a fixed set of shapes the way a range of numbers is, so the compiler cannot see that the three arms are the only ones the program will ever produce. {} is an empty block: an arm that does nothing.

Reference

Written asWhat it does
if cond { … }Run the block only when cond is true.
if cond { … } else { … }Run one block or the other.
else if cond { … }Add another condition to check next.
let x = if … { a } else { b }Use if as an expression.
match value { … }Pick one arm. Every case must be covered.
0..=9 => …An arm matching a range, both ends included.
1 | 2 | 3 => …An arm matching several values.
n if n % 2 == 0 => …An arm with a guard.
c @ 1..=9 => …Bind the matched value to c.
_ => …The arm that matches anything left over.
if let 0 = count { … }Run a block only if one pattern fits.
loop { … }Repeat forever until break.
break;Leave the innermost loop.
break value;Leave a loop with a value.
continue;Skip to the next pass of the loop.
‘outer: loop { … }Label a loop so it can be named later.
break ‘outer;Leave the labelled loop, not just the inner one.
while cond { … }Repeat while cond stays true.
a..bA range from a up to b, not including b.
a..=bA range from a up to b, including b.
for x in a..b { … }Step through a range.
for x in &array { … }Step through an array by reference.
array.iter().enumerate()Pair each value with its position.

Check what stuck

The practice sheet for this lesson has 50 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.

Start practice →