Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ EXPRESS THE WORK
BUILD NOTE 07 / 53

Repeat with an exit plan.

Choose the loop that makes termination and iteration clearest.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

Use for to iterate over a range or collection, while for a condition checked before each iteration, and loop when the exit is controlled inside the body. break exits and continue skips to the next iteration. A loop expression can return a value with break value. Ranges such as 0..3 exclude the end, while 0..=3 include it. A simple termination argument is useful even in everyday code: explain what changes on every iteration and why an exit must eventually happen.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/loops/src/main.rs
fn main() {
    let sum: i32 = (1..=4).sum();
    let mut n = 0;
    let found = loop {
        n += 1;
        if n * n >= 20 {
            break n;
        }
    };
    println!("sum={sum}, first square boundary={found}");
}
↳ EXPECTED OUTPUT
sum=10, first square boundary=5
  1. 1

    The inclusive range contributes 1, 2, 3, and 4.

  2. 2

    n increases each iteration until its square reaches the threshold.

  3. 3

    break n gives the loop its result.

From the extracted rust-workbench folder
cargo run -p lesson_loops

03 Mind the boundary

04 Your next build

A SMALL MISSION

Use a for loop to collect multiples of three from 1 through 10.

Reveal one possible solution +
solutions/loops/src/main.rs
fn main() {
    let mut values = Vec::new();
    for n in 1..=10 {
        if n % 3 == 0 {
            values.push(n);
        }
    }
    assert_eq!(values, [3, 6, 9]);
}

05 Check your reasoning

QUICK SIGNAL CHECK

Which values are in 1..4?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.