Lesson 5 / 25

if, loop and match

Explain if, loop and match, run a focused Rust example, and interpret the compiler result.

The essential idea

if, loop and match helps Rust programs remain clear and safe. First name the value involved, who may use it, and when it stops being valid. That question matters more than memorising punctuation.

Trace the loop

A Rust source file is checked and built by Cargo before the program runs. This topic changes one safe part of that path.

let mut sum = 0;
for n in 1..=3 {
    sum += n;
}
println!("{sum}");

Output:

6
  1. Line 1: The accumulator starts before the iterator yields a number.
  2. Line 2: The inclusive range yields 1 first, so the body runs.
  3. Line 3: The total changes inside the body, not at print time.
  4. Line 5: After 3, the iterator finishes and the complete total prints.

Read the compiler message

Rust errors can feel strict at first. They are usually telling you which value moved, which borrow overlaps, or which type is expected. Reduce the example and fix one message at a time.

Quick check

Quick check: What is a sound way to learn if, loop and match?

  • Make a small example and use compiler feedback.
  • Ignore ownership and error messages.
  • Copy code without running it.
Answer

Make a small example and use compiler feedback. — A small compiled experiment turns an abstract rule into visible evidence.