Rust•Loop Control
Rust Break and Continue Statements with Loop Labels
break exits the loop; continue advances to next iteration. Use loop labels ('label:) to escape nested loops.
Syntax
if condition { break; }
if condition { continue; }
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| break | Keyword | Terminates loop execution. |
| continue | Keyword | Skips current iteration. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Rust locally:
fn main() {
let readings = [22, 24, -1, 26, 999, 28];
println!("Processing sensor readings:");
for val in readings {
if val < 0 {
println!(" [SKIP] Glitch reading: {}", val);
continue;
}
if val == 999 {
println!(" [HALT] Sentinel 999 detected! Shutting down.");
break;
}
println!(" [OK] Temperature: {}C", val);
}
}Expected Output:
Processing sensor readings: [OK] Temperature: 22C [OK] Temperature: 24C [SKIP] Glitch reading: -1 [OK] Temperature: 26C [HALT] Sentinel 999 detected! Shutting down.
How It Works: Step-by-Step
- Lines 7-10: continue skips -1.
- Lines 11-14: break halts loop upon 999.
Key Concepts
- continue skips straight to the next iteration.
- break terminates only the innermost loop unless a label is specified.
Common Mistake: Placing break before necessary state mutations
Statements after break within the same block are unreachable.
❌ Incorrect
if done { break; count += 1; } // Warning: unreachable statement✅ Correct
if done { count += 1; break; }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 While Loops: Conditional Iteration with Examples
Execute code conditionally with while and while let in Rust.
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.