</>
Skip to content
Rust lessons (15/43)

Rust — While Loops

Three kinds of loops

while condition { … }        // repeat while true
loop { … }                   // forever (until break)
for x in collection { … }    // iterate everything

while — condition-driven

let mut count = 3;

while count > 0 {
    println!("{}", count);
    count -= 1;
}
println!("Liftoff!");

Condition checked before each pass; the mut counter must march toward false or you hang the program.

loop + break = a value-producing infinite loop

Rust's loop is deliberate "run until told otherwise" — and it can RETURN a value via break:

let mut attempts = 0;

let result = loop {
    attempts += 1;

    if attempts * attempts > 50 {
        break attempts;         // ← loop evaluates to this
    }
};

println!("stopped at {}", result);   // 8

break value; makes the whole loop expression evaluate. Only bare loop can do this (while/for always return ()).

The canonical use: retry logic

let connection = loop {
    match try_connect() {
        Ok(conn) => break conn,       // success → exit WITH the connection
        Err(_) => continue,           // retry
    }
};

break / continue

let mut i = 0;

while i < 10 {
    i += 1;
    if i % 2 == 0 { continue; }   // skip evens
    if i > 7 { break; }           // stop past 7
    println!("{}", i);
}
// prints 1, 3, 5, 7

Labeled loops — breaking nested ones

break exits only the innermost loop. Labels target outer ones:

'outer: for row in grid {
    for cell in row {
        if cell == TARGET {
            break 'outer;         // exits BOTH loops
        }
    }
}

Labels start with an apostrophe. Same syntax works for continue 'outer.

while vs for vs loop

SituationPick
Visit every item of a collectionfor (always safer)
Repeat exact countfor … in range
Condition may never become false / retry patternwhile
Need the exit VALUE / intentional infiniteloop

Rule of thumb: if you're writing while i < list.len(), stop — that's what for is for. Reach for while only when no collection exists to iterate.

Gotchas: forgetting the counter update (infinite) · using while over a Vec when a for would avoid index-out-of-bounds risks entirely.

Mini Practice

  1. Countdown 10→0 with while.
  2. Digit-sum of a number using % 10 and / 10.
  3. loop+break returning first square above 500.
  4. Menu loop reading input until "quit".
  5. Nested grid search breaking both loops with a label.

Next: for loops →

Related Topics

Frequently Asked Questions about While Loops

What is While Loops in Rust?

While Loops is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn While Loops?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn While Loops.

Why is While Loops important in Rust?

While Loops is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.