Rust•Loops
Rust Zero-Cost Sequence Parsing Iterators and For Loops
In Rust, for loops and iterators are zero-cost abstractions: the compiler optimizes high-level iterator pipelines (.iter(), .filter(), .map()) into hand-written assembly without bounds checking overhead. Understanding ownership during iteration (borrowing with & vs moving with into_iter()) is vital for writing performant systems software.
Syntax
for item in &collection { ... } // Borrowed iteration
for item in collection { ... } // Consuming iteration (moves collection)
let val = loop { break result; }; // Value-returning loop
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| for item in &collection | Borrowing Loop | Borrows references to elements without moving or consuming collection. |
| into_iter() | Iterator | Consumes the collection by value, transferring ownership of each element. |
| loop { break expr; } | Expression Loop | Infinite loop that returns a computed expression upon break. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Rust locally:
fn main() {
println!("=== Rust Zero-Cost Sequence Parsing & Iterators ===");
// 1. Borrowed vector iteration (preserves collection ownership)
let microservices = vec!["auth-service", "gateway-api", "event-broker", "cache-worker"];
println!("--- 1. Iterating Borrowed Vector Slice ---");
for (idx, service) in microservices.iter().enumerate() {
println!("Service #{}: {}", idx + 1, service);
}
// microservices is still completely valid here because we borrowed with .iter()
println!("Total Registered Services: {}\n", microservices.len());
// 2. Functional iterator adapter pipeline (zero allocation)
println!("--- 2. Iterator Pipeline: Filter & Transformation ---");
let latencies_ms = vec![12, 45, 110, 8, 230, 95];
let slow_requests_count = latencies_ms
.iter()
.filter(|&&lat| lat > 50)
.count();
println!("Slow Requests (>50ms): {} / {}", slow_requests_count, latencies_ms.len());
// 3. Value-returning loop expression
println!("\n--- 3. Value-Returning Loop Expression ---");
let mut retry_attempt = 0;
let final_status = loop {
retry_attempt += 1;
println!("Handshake Attempt #{}...", retry_attempt);
if retry_attempt == 3 {
break "CONNECTION_ESTABLISHED_200_OK"; // Returns value from loop expression
}
};
println!("Loop Expression Resolved: {}", final_status);
}Expected Output:
=== Rust Zero-Cost Sequence Parsing & Iterators === --- 1. Iterating Borrowed Vector Slice --- Service #1: auth-service Service #2: gateway-api Service #3: event-broker Service #4: cache-worker Total Registered Services: 4 --- 2. Iterator Pipeline: Filter & Transformation --- Slow Requests (>50ms): 3 / 6 --- 3. Value-Returning Loop Expression --- Handshake Attempt #1... Handshake Attempt #2... Handshake Attempt #3... Loop Expression Resolved: CONNECTION_ESTABLISHED_200_OK
How It Works: Step-by-Step
- Lines 6-10: Iterates over borrowed elements via .iter().enumerate(); vector remains owned by main().
- Lines 16-20: Uses zero-cost iterator adapters (.filter().count()) without allocating intermediate vectors.
- Lines 25-33: Demonstrates loop as an expression returning a string slice via break expr.
Key Concepts
- Rust iterators compile down to raw pointers and assembly loops with zero runtime abstraction penalty.
- Using for x in &vec borrows elements; for x in vec consumes ownership of the vector elements.
- The loop construct is an expression that can return values directly using break value;.
- Iterator chaining (filter, map, enumerate) evaluates lazily, executing only when a consumer like .count() or .collect() is called.
Common Mistake: Accidentally moving a collection inside a for loop
Writing for x in vec moves ownership of vec into the loop. Attempting to use vec afterward triggers a compile-time "use of moved value" error.
❌ Incorrect
for x in vec { println!("{}", x); }
println!("{}", vec.len()); // Compile Error: use of moved value: `vec`✅ Correct
for x in &vec { println!("{}", x); }
println!("{}", vec.len()); // Correct: borrowed iterationRelated Rust Tutorials & Compiler
Rust While Loops: Conditional Iteration with Examples
Execute code conditionally with while and while let in Rust.
Rust Break and Continue Statements with Loop Labels
Interrupt or skip loop cycles with break, continue, and labeled loop escapes.
Rust Vectors (Vec<T>): Dynamic Heap Arrays and Slices
Master dynamic Vec<T> collections using vec! macro, push, pop, and indexing.
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.