TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
for loop in Rust is an iteration construct that executes a block of code for each element yielded by an iterator. It operates as syntactic sugar for an infinite loop that continuously invokes the next method on an Iterator trait implementation, automatically matching on the Option::None variant to safely terminate execution.
Trait Mechanics
Thefor loop strictly requires the iterable expression to implement the IntoIterator trait. Upon initialization, the compiler implicitly invokes IntoIterator::into_iter(iterable) to construct the underlying iterator.
During each iteration, the loop evaluates Iterator::next(). If the method returns Some(value), the value is destructured or bound to the specified pattern, and the loop body executes. If it returns None, the loop terminates.
Desugared Representation
To understand the exact control flow and lifetime semantics, a standardfor loop translates to a lower-level match expression during compilation. Using a match block rather than a let binding is a critical semantic distinction: it safely extends the lifetime of any temporary values evaluated in the iterator expression for the entire duration of the loop. This prevents borrow checker errors that would occur if a temporary were dropped at the end of a standard let statement.
Ownership and Borrowing Semantics
Because thefor loop consumes the iterator via into_iter(), the ownership state of the yielded elements is dictated by the reference type of the iterable provided:
- By Value (
iterable): Consumes the collection.IntoIteratoryields owned values (T). The original collection is moved and becomes inaccessible after the loop. - By Immutable Reference (
&iterable): Borrows the collection.IntoIteratoryields immutable references (&T). This is semantically equivalent to calling.iter(). - By Mutable Reference (
&mut iterable): Mutably borrows the collection.IntoIteratoryields mutable references (&mut T). This is semantically equivalent to calling.iter_mut().
Control Flow Modifiers
The execution of afor loop can be manually altered using standard control flow keywords:
continue: Bypasses the remaining statements in the current iteration block and immediately evaluates the nextIterator::next()call.break: Immediately halts the loop, dropping the iterator. Unlike theloopconstruct,breakinside aforloop cannot return a value; aforloop always evaluates to the unit type().
Loop Labels
For nested iteration,for loops can be annotated with lifetime-like labels. This allows break and continue statements to target specific outer loops rather than the immediate enclosing loop.
Master Rust with Deep Grasping Methodology!Learn More





