> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Rust For Loop

The `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.

```rust theme={"dark"}
fn main() {
    let iterable = [1, 2, 3];
    
    for pattern in iterable {
        println!("{}", pattern);
    }
}
```

## Trait Mechanics

The `for` 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 standard `for` 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.

```rust theme={"dark"}
fn main() {
    let iterable = vec![1, 2, 3];

    // Standard for loop
    for val in iterable.clone() {
        println!("{}", val);
    }

    // Desugared equivalent
    match IntoIterator::into_iter(iterable) {
        mut iter => loop {
            match iter.next() {
                Some(val) => {
                    println!("{}", val);
                },
                None => break,
            }
        }
    }
}
```

## Ownership and Borrowing Semantics

Because the `for` 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. `IntoIterator` yields owned values (`T`). The original collection is moved and becomes inaccessible after the loop.
* **By Immutable Reference (`&iterable`)**: Borrows the collection. `IntoIterator` yields immutable references (`&T`). This is semantically equivalent to calling `.iter()`.
* **By Mutable Reference (`&mut iterable`)**: Mutably borrows the collection. `IntoIterator` yields mutable references (`&mut T`). This is semantically equivalent to calling `.iter_mut()`.

```rust theme={"dark"}
fn main() {
    let mut collection = vec![1, 2, 3];

    // Yields &T (Borrows collection)
    for val in &collection {
        println!("Read-only: {}", val);
    }

    // Yields &mut T (Mutably borrows collection)
    for val in &mut collection {
        *val += 1;
    }

    // Yields T (Moves collection)
    for val in collection {
        println!("Owned: {}", val);
    }
    // 'collection' is no longer accessible here
}
```

## Control Flow Modifiers

The execution of a `for` loop can be manually altered using standard control flow keywords:

* `continue`: Bypasses the remaining statements in the current iteration block and immediately evaluates the next `Iterator::next()` call.
* `break`: Immediately halts the loop, dropping the iterator. Unlike the `loop` construct, `break` inside a `for` loop cannot return a value; a `for` loop 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.

```rust theme={"dark"}
struct Element {
    value: i32,
}

impl Element {
    fn is_invalid(&self) -> bool {
        self.value < 0
    }
}

fn main() {
    let matrix = vec![
        vec![Element { value: 1 }, Element { value: 2 }],
        vec![Element { value: -1 }, Element { value: 3 }],
        vec![Element { value: 4 }, Element { value: 5 }],
    ];

    'outer: for x in &matrix {
        for y in x {
            if y.is_invalid() {
                println!("Invalid element found, skipping row.");
                continue 'outer;
            }
            println!("Processing: {}", y.value);
        }
    }
}
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Rust Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
