Rust:Rust While Loops: Conditional Iteration with Examples
Rust•Loops

Rust While Loops: Conditional Iteration with Examples

Use while loops when the iteration depends on a boolean predicate, or while let to consume streams.

Syntax

while condition { // body }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
whileLoopRe-evaluates condition before each iteration.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Rust locally:

fn main() {
    let mut countdown = 3;
    println!("--- Rocket Countdown ---");
    while countdown > 0 {
        println!("T-minus {}...", countdown);
        countdown -= 1;
    }
    println!("Liftoff! 🚀");
}
Expected Output:
--- Rocket Countdown ---
T-minus 3...
T-minus 2...
T-minus 1...
Liftoff! 🚀

How It Works: Step-by-Step

  • Lines 4-7: while loop decrements countdown until 0.

Key Concepts

  • while evaluates condition on each iteration.
  • while let pattern = expr loops as long as pattern matches.

Common Mistake: Forgetting mut on loop counter variable

In Rust, variables must be declared let mut to be modified inside loops.

❌ Incorrect
let count = 3;
while count > 0 { count -= 1; } // Compile Error: cannot assign to immutable variable
✅ Correct
let mut count = 3;
while count > 0 { count -= 1; }

Related Rust Tutorials & Compiler

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler