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:
| Parameter | Type | Description |
|---|---|---|
| while | Loop | Re-evaluates condition before each iteration. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Rust Zero-Cost Sequence Parsing Iterators and For Loops
Master Rust zero-cost iterator loops: borrowed iteration (&vec), iterator adapters (filter, count), and value-returning infinite loop expressions.
Rust Break and Continue Statements with Loop Labels
Interrupt or skip loop cycles with break, continue, and labeled loop escapes.
Rust Exhaustive Match Pattern Matching and Expression Control Flow
Master expression-driven pattern matching in Rust using exhaustive match blocks, match guards, range patterns (..=), and wildcards (_).
Rust Online Compiler
Open in Compilra IDE
Run and test Rust on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.