Repeating Logic with Loops

Repeating Logic with Loops in Rust: Three jobs at the same depot, and three completely different ways of knowing when you are finished.

The Analogy: The Belt, the Kettle, and the Night Watchman

Three jobs at the same depot, and three completely different ways of knowing when you are finished. The first is the packing station, where parcels come down a conveyor belt. You take one, wrap it, put it in the bin, and reach for the next. You never count parcels and you never ask "is there another one?" -- the belt answers that by stopping. When it stops, you are done, and it is impossible for you to reach past the end of the belt because there is nothing there to reach for.

The second is the kettle in the break room. You have no idea how many times you will have to look at it. So you check the condition, wait, check again, and eventually the condition is false and you pour. The number of iterations is not known in advance and is not the point; the condition is the point, and it sits in front of you where you can read it every pass.

The third is the night watchman. Their patrol has no natural end at all -- they walk the corridors until something happens. And when it does, they do not merely stop; they come back with a note saying what happened. "All clear at 03:00." "Door 4 unlatched." The patrol is open-ended by design, and its whole value is the answer it brings back.

Rust gives you exactly these three, and the belt is the one to reach for. for iterates a sequence and has no index and no bounds expression -- which is why the off-by-one and the read-past-the-end, two of the most productive bug families in C, simply have nowhere to live. while is the kettle: a condition, re-read each pass. And loop is the watchman, the only one of the three that is an expression: break can carry a value out, so let outcome = loop { ... }; is idiomatic rather than clever. Reach for for by default, while when the condition is the subject, and loop when the decision to stop is discovered inside the body.


Syntax or Core Structure

Every loop form Rust has, in one program, including labels and the value-carrying break:

fn main() {
    // `for` over a range. There is no index variable and no bounds test.
    for i in 1..4 {
        print!("{i},");
    }
    println!("done");

    // `enumerate` supplies the index when you actually need it.
    let names = ["ada", "linus", "grace"];
    for (i, name) in names.iter().enumerate() {
        println!("{i}: {name}");
    }

    // `while` keeps the condition in front of you.
    let mut countdown = 3;
    while countdown > 0 {
        print!("{countdown}.. ");
        countdown -= 1;
    }
    println!("liftoff");

    // `loop` is the honest infinite loop, and `break` carries a value out.
    let mut tries = 0;
    let found = loop {
        tries += 1;
        if tries * tries > 50 {
            break tries;
        }
    };
    println!("first n with n*n > 50 is {found} (after {tries} tries)");

    // `continue` abandons one pass, not the loop.
    let mut sum = 0;
    for n in 1..=10 {
        if n % 3 == 0 {
            continue;
        }
        sum += n;
    }
    println!("sum skipping multiples of 3 = {sum}");

    // A label lets `break` target an outer loop instead of the nearest one.
    let grid = [[1, 9, 3], [4, 5, 6]];
    let mut hit = None;
    'outer: for (r, row) in grid.iter().enumerate() {
        for (c, value) in row.iter().enumerate() {
            if *value == 9 {
                hit = Some((r, c));
                break 'outer;
            }
        }
    }
    println!("hit = {hit:?}");
}

Output:

1,2,3,done
0: ada
1: linus
2: grace
3.. 2.. 1.. liftoff
first n with n*n > 50 is 8 (after 8 tries)
sum skipping multiples of 3 = 37
hit = Some((0, 1))

Two details in there are easy to skim past. break tries is only legal because the loop is a loop -- the same line in a while is a compile error. And break 'outer needs the label because a bare break in a nested loop exits only the inner one, which is the single most common cause of "my search kept going after it found the thing".


Technical Depth: Iterators, Ownership, and What for Really Compiles To

The four forms at a glance

FormStops whenValue it produces
for x in iterthe iterator yields Nonealways ()
while condthe condition is falsealways ()
while let PAT = exprthe pattern stops matchingalways ()
loopa break executesthe break value, or (), or ! if nothing breaks

Only loop can produce a value. break 7 inside a while is error[E0571]: break with value from a while loop, and the same applies to for. The reason is straightforward: a while that ends because its condition went false has no value to offer, so the language refuses to let the two exits disagree.

for is sugar, and the sugar is the safety

There is no C-style for (init; test; step) in Rust. for desugars to an iterator drive:

for x in collection {
    body(x);
}

// is roughly:
let mut it = IntoIterator::into_iter(collection);
while let Some(x) = it.next() {
    body(x);
}

Everything follows from that. There is no bounds expression, so you cannot write it wrong. There is no index, so you cannot index out of range. And crucially, which IntoIterator you get decides what happens to the collection:

What you writeItem typeEffect on the collection
for x in vTConsumes v. It is moved and unusable afterwards
for x in &v&TBorrows immutably; v is fine afterwards
for x in &mut v&mut TBorrows mutably; you can write through x
for x in v.iter()&TIdentical to &v
for x in v.iter_mut()&mut TIdentical to &mut v
for x in v.into_iter()TIdentical to v

That first row is the one that bites. for line in lines { ... } followed by lines.len() is error[E0382]: borrow of moved value, and the fix is a single &. Arrays of Copy types are the exception that makes it confusing -- for n in [1, 2, 3] copies each element and leaves the array intact, so the move only shows up once your elements are Strings.

Ranges, including the ones that surprise people

Range expressionYields
0..50 1 2 3 4
0..=50 1 2 3 4 5
(0..5).rev()4 3 2 1 0
(0..10).step_by(3)0 3 6 9
0..0nothing
5..0nothing -- a range never counts down on its own
'a'..='e'the five chars a b c d e

5..0 yielding an empty sequence rather than counting backwards is worth burning in: to descend you need .rev() on an ascending range. And .rev() requires DoubleEndedIterator, which 0.. (an unbounded RangeFrom) is not -- (0..).rev() fails with error[E0277] because an infinite range has no last element to start from.

Labels, and while let

A label is an identifier with a leading apostrophe, written before the loop keyword. It works on all three loop forms, and since Rust 1.65 on a plain block too:

  • break 'outer; -- leave the labelled loop.
  • continue 'outer; -- start the labelled loop's next pass.
  • break 'outer value; -- leave a labelled loop with a value.
  • 'block: { ... break 'block value; } -- a labelled block, useful as an early exit from a computation without a function.

while let is the loop version of if let: it runs as long as the pattern keeps matching, which makes draining a collection a two-line affair.

Here is all of that, running:

fn main() {
    let words = vec![String::from("alpha"), String::from("beta")];

    // Borrow: `words` survives the loop.
    for w in &words {
        print!("{w} ");
    }
    println!("| still have {} words", words.len());

    // Mutable borrow: write through the item.
    let mut nums = vec![1, 2, 3];
    for n in &mut nums {
        *n *= 10;
    }
    println!("nums = {nums:?}");

    // Consume: after this line `words` no longer exists.
    let mut joined = String::new();
    for w in words {
        joined.push_str(&w);
        joined.push('/');
    }
    println!("joined = {joined}");

    // Ranges.
    let up: Vec<i32> = (0..5).collect();
    let down: Vec<i32> = (0..5).rev().collect();
    let stepped: Vec<i32> = (0..10).step_by(3).collect();
    let backwards: Vec<i32> = (5..0).collect();
    println!("up        = {up:?}");
    println!("down      = {down:?}");
    println!("stepped   = {stepped:?}");
    println!("backwards = {backwards:?}");

    // `while let` drains a stack from the top.
    let mut stack = vec![1, 2, 3];
    while let Some(top) = stack.pop() {
        print!("{top} ");
    }
    println!("(empty: {})", stack.is_empty());
}

Output:

alpha beta | still have 2 words
nums = [10, 20, 30]
joined = alpha/beta/
up        = [0, 1, 2, 3, 4]
down      = [4, 3, 2, 1, 0]
stepped   = [0, 3, 6, 9]
backwards = []
3 2 1 (empty: true)

Note the ordering constraint that program had to respect: words.len() is called before the consuming loop, because after for w in words the vector is gone. Swap those two blocks and the program does not compile -- which is the whole point.


Real World Example: Paginating Through an API

Cursor pagination is the textbook case for loop, because you cannot know whether to continue until after you have made the request. A while header would have to either duplicate the fetch or invent a sentinel flag; loop puts the decision exactly where the information arrives.

struct Page {
    items: Vec<&'static str>,
    next: Option<u32>,
}

/// Stand-in for a network call: page 0 -> 1 -> 2, then no cursor.
fn fetch(cursor: Option<u32>) -> Page {
    match cursor {
        None => Page { items: vec!["ada", "linus"], next: Some(1) },
        Some(1) => Page { items: vec!["grace", "alan", "edsger"], next: Some(2) },
        Some(2) => Page { items: vec!["barbara"], next: None },
        Some(_) => Page { items: Vec::new(), next: None },
    }
}

/// Returns everything it could fetch, how many pages it took, and whether
/// it stopped early because of the page cap.
fn collect_all(max_pages: u32) -> (Vec<&'static str>, u32, bool) {
    let mut all = Vec::new();
    let mut cursor = None;
    let mut pages = 0;

    let truncated = loop {
        let page = fetch(cursor);
        pages += 1;
        all.extend(page.items);

        // No cursor means we have the whole set: leave with `false`.
        let Some(next) = page.next else {
            break false;
        };
        // A cursor but no budget left: leave with `true`.
        if pages >= max_pages {
            break true;
        }
        cursor = Some(next);
    };

    (all, pages, truncated)
}

fn main() {
    let (names, pages, truncated) = collect_all(10);
    println!("pages     = {pages}");
    println!("truncated = {truncated}");
    println!("count     = {}", names.len());
    for (i, name) in names.iter().enumerate() {
        println!("  {:>2}. {name}", i + 1);
    }

    let (short, pages, truncated) = collect_all(2);
    println!();
    println!("capped at 2: {} names over {pages} pages, truncated = {truncated}", short.len());
}

Output:

pages     = 3
truncated = false
count     = 6
   1. ada
   2. linus
   3. grace
   4. alan
   5. edsger
   6. barbara

capped at 2: 5 names over 2 pages, truncated = true

The loop is the expression that produces truncated. Compare that with the shape you would write in most languages: declare let mut truncated = false; at the top, mutate it in one of two places deep inside the body, and hope no third exit gets added later that forgets to set it. Here there are exactly two ways out, both are break, and both are forced to name the answer. If you add a third exit, you cannot forget -- break; with no value will not typecheck against the other two.

The let Some(next) = page.next else { break false; }; line deserves a second look, because it is doing something let ... else is often not credited with. The else block only has to diverge, and break diverges just as much as return does. So bind-or-bail works inside a loop, bailing out of the loop rather than the function, and the happy path -- next is in scope for the rest of the body -- stays at the outer indentation.

The page cap is not defensive clutter; it is a requirement. Any loop whose termination depends on data you do not control needs a bound, because "the server keeps handing back a cursor" is a real failure mode and an unbounded loop turns it into an unbounded memory allocation. The interesting part is that collect_all reports whether it hit the cap instead of silently returning a short list, so the caller can tell "that is everything" apart from "that is the first two pages". A function that quietly truncates is worse than one that fails.

Note also all.extend(page.items), which moves the items out of page and then still reads page.next on the next line. That is a partial move, and it is legal: once page.items has been given away, the rest of page is still yours. If Page had a method that needed &self, though, calling it after the extend would fail -- you cannot borrow a value you have taken a piece out of.


Common Mistakes

  1. for x in v when you meant for x in &v. The loop consumes the collection, and the next line that touches it fails with error[E0382]: borrow of moved value. The compiler's suggestion is literally to add the &. Because arrays of Copy elements do not move, this bug hides until your elements become Strings.
  1. Mutating a collection while iterating it. for x in &v { v.push(*x); } gives error[E0502]: cannot borrow v as mutable because it is also borrowed as immutable. Other languages let you write this and then either corrupt the iterator or throw at run time. Collect the changes into a second Vec and apply them after the loop.
  1. Hand-rolling the index loop. let mut i = 0; while i < v.len() { ... } reintroduces both classic bugs at once: forget i += 1 and it never ends, write <= and it panics with index out of bounds. Use for, and .enumerate() if you genuinely need the number.
  1. break value from a for or while. Only loop is an expression. You get error[E0571]. If you want a value out of a search, either restructure as a loop or use an iterator method such as find or position.
  1. Expecting 5..0 to count down. It yields nothing at all, and there is no error and no warning -- the loop body simply never runs. Descending needs (0..5).rev().
  1. for i in 0..v.len() followed by v[i]. It compiles and it is correct, but you have re-created the bounds expression you were trying to avoid, and every v[i] is a checked index the iterator version would not need. Reserve it for the rare case where you index two collections in step.
  1. A bare break inside nested loops. It leaves only the innermost loop, so the outer one keeps going with a result already found. Label the outer loop and break 'outer.
  1. Off-by-one from .. versus ..=. for i in 1..n stops at n - 1. Nothing warns you, and the symptom is one missing item at the end of a report -- the hardest kind of bug to notice.
  1. A loop whose break is unreachable. The loop's type becomes !, everything after it is dead, and rustc says warning: unreachable_code while your program hangs. If a loop can only be exited by return or panic!, say so in a comment, because the next reader will assume you forgot the break.

Best Practices

  • Default to for over an iterator. Reach for while only when a condition is genuinely the subject, and for loop only when the stop decision is discovered inside the body.
  • Iterate by reference (&v or &mut v) unless you specifically want the collection consumed. Write the & first and remove it if the compiler tells you the values need to be owned.
  • Let loop return the answer with break value instead of mutating a flag declared above it. Two exits that must both name the answer cannot silently disagree.
  • Bound every loop whose termination depends on external data, and report whether the bound was hit rather than returning a quietly truncated result.
  • Label nested loops you intend to break out of, and label them meaningfully -- 'rows and 'search read better than 'outer once there are three of them.
  • Prefer while let Some(x) = queue.pop() to a loop with a match and a break. It is the same machine with less to read.
  • Do not compute v.len() in a condition you could avoid entirely, and never index inside a loop you could have written with .iter(). Fewer index expressions means fewer places a bound can be wrong.
  • Once a loop is only accumulating -- summing, counting, filtering, or building a Vec -- consider whether an iterator adapter says it more plainly. Module 7 covers map, filter, sum, and collect, and they replace a large fraction of the loops people write.

Practice Exercises

  1. The three shapes, one problem. Write three functions that each find the first index of target in a &[i32], returning Option<usize>: one with for and .enumerate(), one with while and a manual index, and one with loop. Test all three with a target that is present, one that is absent, and an empty slice, then decide which you would actually ship and why.
  1. Collatz with a budget. Write fn collatz_steps(mut n: u64, max_steps: u32) -> Option<u32> that counts how many steps n takes to reach 1 (halve if even, otherwise 3n + 1), returning None if it exceeds max_steps. Use loop with two breaks carrying different values. Print the step count for 6, 27, and 1.
  1. Break out of a grid. Given a [[u8; 4]; 4] grid, find the coordinates of the first zero using labelled loops, and make the search return Option<(usize, usize)> from a labelled loop rather than assigning to a mutable variable. Then rewrite it as a single for over .iter().enumerate().flat_map(...) and compare which one you would rather debug.
  1. Prove the move. Take the pagination example and change items: Vec<&'static str> to items: Vec<String>, then try to print page.items.len() after the all.extend(page.items) line. Read the error carefully, fix it two different ways (once by moving the len() call earlier, once by passing &page.items and cloning), and write down which fix you would choose for a hot loop.