How to Use Loops in Rust: Syntax, Examples, and Practical Uses

In Rust, iteration is structured around three native constructs: loop, while, and for. While most C-family languages treat repetition primarily as conditional statements, Rust designs loops as expressions that integrate directly into the language’s type system, ownership mechanics, and control-flow analysis.

Understanding loops in Rust requires looking beyond basic syntax. The compiler’s borrow checker enforces strict guarantees around memory safety during iteration, while the language’s design eliminates common pitfalls such as off-by-one errors and array bounds checks. Each loop construct serves a distinct architectural purpose in systems programming, ranging from low-level polling loops to zero-cost collection traversal.

The Unconditional Loop: loop

The simplest looping construct in Rust is loop. It executes a block of code indefinitely until an explicit interruption occurs, such as a break statement, a return, or an unhandled panic.

fn main() {
    let mut counter = 0;

    loop {
        counter += 1;
        println!("Counter: {counter}");

        if counter == 5 {
            break;
        }
    }
}

Compiler Analysis and the Never Type

Unlike other languages where developers typically write while (true) or for (;;), Rust provides loop as a first-class language feature. The distinction is functional rather than stylistic.

When the Rust compiler analyzes a while true construct in other languages, it must evaluate a conditional expression that could theoretically change. In contrast, Rust’s compiler recognizes loop as inherently non-terminating. In static analysis, this allows the compiler to prove that any code immediately following a loop without a break is completely unreachable.

In type system terms, a non-terminating loop evaluates to the “never type,” represented by an exclamation point (!). This guarantees that variables initialized inside a loop can satisfy the compiler’s definite initialization analysis if execution cannot continue past the block without that variable being assigned.

Returning Values from loop Expressions

Because loop is an expression, it can produce a value. This is achieved by passing an expression directly to the break keyword:

fn fetch_resource() -> Result<String, ()> {
    // Simulated intermittent resource retrieval
    Ok(String::from("payload"))
}

fn main() {
    let mut attempts = 0;

    let data = loop {
        attempts += 1;

        match fetch_resource() {
            Ok(payload) => break payload,
            Err(_) if attempts >= 3 => break String::from("fallback"),
            Err(_) => continue,
        }
    };

    println!("Acquired data: {data}");
}

This pattern is widely used in systems programming for retry operations, network polling, and lock acquisition. Instead of declaring a mutable variable outside the loop and assigning it upon success, the assignment is handled atomically at the site of the break, allowing the resulting variable (data) to remain immutable.

Conditional Execution: while

The while loop evaluates a boolean predicate before each iteration. The loop runs as long as the condition evaluates to true and terminates immediately when the condition evaluates to false.

fn main() {
    let mut number = 3;

    while number != 0 {
        println!("{number}!");
        number -= 1;
    }

    println!("Liftoff!");
}

Unlike loop, a while loop cannot return a value via break. Because a while loop can terminate conditionally without hitting an explicit break, it always evaluates to the unit type ().

Pattern Matching with while let

When a conditional loop depends on repeatedly unwrapping an Option or Result until a terminating state is reached, the idiomatic construct is while let. This combines the conditional mechanics of while with Rust’s pattern matching:

fn main() {
    let mut task_queue = vec!["disk_cleanup", "sync_cache", "flush_logs"];

    // Continues popping until task_queue.pop() returns None
    while let Some(task) = task_queue.pop() {
        println!("Executing: {task}");
    }
}

Using while let avoids the manual error-handling boilerplate of checking whether a collection is empty, indexing it, and handling unwraps separately.

Iterating Over Collections: for

Rust does not provide a C-style three-part for loop (for (int i = 0; i < n; i++)). Instead, the for construct is entirely iterator-driven, traversing any type that implements the IntoIterator trait.

fn main() {
    let environments = ["production", "staging", "development"];

    for env in environments {
        println!("Target environment: {env}");
    }
}

The Elimination of Bounds Checking

In languages that rely on index-based iteration, every access to an array element must check the index against the array’s length at runtime to avoid out-of-bounds memory corruption. This introduces runtime overhead and opens the door to off-by-one errors.

In Rust, the for loop queries the collection’s iterator directly. Because the iterator maintains internal state that cannot exceed the collection’s bounds, the compiler can completely omit runtime bounds checks for the iteration, producing machine code that is both safer and faster.

Ownership, Borrowing, and Iteration Tiers

How a collection is traversed depends on how ownership is handed to the for loop. Rust distinguishes between three iteration modes based on ownership semantics:

1. Immutable Borrowing (&collection or .iter())

When data needs to be inspected without transferring ownership or modifying elements:

fn main() {
    let servers = vec![String::from("auth-1"), String::from("db-1")];

    for server in &servers {
        println!("Pinging: {server}");
    }

    // The collection remains accessible after the loop
    println!("Total servers monitored: {}", servers.len());
}

2. Mutable Borrowing (&mut collection or .iter_mut())

When elements must be modified in place:

fn main() {
    let mut metrics = vec![12.4, 15.8, 9.2];

    for metric in &mut metrics {
        *metric *= 1.10; // 10% calibration adjustment
    }

    println!("Adjusted metrics: {metrics:?}");
}

3. Moving Ownership (collection or .into_iter())

When the loop must take ownership of the elements, consuming the collection in the process:

fn process_record(record: String) {
    println!("Consumed: {record}");
}

fn main() {
    let records = vec![String::from("rec_01"), String::from("rec_02")];

    for record in records {
        process_record(record); // Ownership moves into the function
    }

    // The following line would fail compilation:
    // println!("Records: {records:?}"); // Error: value borrowed here after move
}

Numeric Ranges

To iterate over a numerical sequence, Rust uses range syntax:

  • a..b: Half-open range (includes a, excludes b).
  • a..=b: Inclusive range (includes both a and b).
fn main() {
    // Print numbers 1 through 4
    for count in 1..5 {
        println!("{count}");
    }

    // Reverse iteration over an inclusive range (5 down to 1)
    for count in (1..=5).rev() {
        println!("{count}");
    }
}

Disambiguating Nested Loops with Labels

When working with nested loops, a standard break or continue statement applies exclusively to the innermost loop enclosing it. In scenarios where an inner condition requires terminating or continuing an outer loop, Rust provides loop labels.

Labels begin with a single quote ('), followed by a descriptive identifier and a colon:

fn find_matrix_value(matrix: &[&[i32]], target: i32) -> Option<(usize, usize)> {
    let mut location = None;

    'rows: for (row_idx, row) in matrix.iter().enumerate() {
        for (col_idx, &val) in row.iter().enumerate() {
            if val == target {
                location = Some((row_idx, col_idx));
                break 'rows; // Exits the outer loop immediately
            }
        }
    }

    location
}

fn main() {
    let grid: [&[i32]; 3] = [
        &[10, 20, 30],
        &[40, 50, 60],
        &[70, 80, 90],
    ];

    if let Some((r, c)) = find_matrix_value(&grid, 50) {
        println!("Target found at row {r}, column {c}");
    }
}

This pattern eliminates the need for boolean flags or sentinel checks across loop nesting boundaries.

Practical Applications: Idiomatic Patterns

Choosing the appropriate loop structure in Rust depends on the architectural requirements of the operation:

1. Polling and Workers with Infinite Loops

In background services, daemons, and embedded systems, threads frequently execute a continuous cycle waiting on events or synchronization primitives:

use std::sync::mpsc::Receiver;

fn worker_loop(rx: Receiver<Job>) {
    loop {
        match rx.recv() {
            Ok(job) => job.execute(),
            Err(_) => {
                // Channel has hung up; terminate the worker cleanly
                eprintln!("Job channel closed. Worker shutting down.");
                break;
            }
        }
    }
}

struct Job;
impl Job {
    fn execute(&self) {}
}

2. State-Dependent Buffer Draining

When reading streams or parsing structured packets, while and while let handle variable-length payloads where termination is determined at runtime:

fn parse_stream(mut stream: &[u8]) {
    while !stream.is_empty() {
        let length = stream[0] as usize;
        if stream.len() < length + 1 {
            eprintln!("Incomplete packet received.");
            break;
        }

        let packet = &stream[1..=length];
        println!("Parsed segment of {} bytes: {packet:?}", packet.len());
        stream = &stream[length + 1..];
    }
}

3. Loops vs. Functional Iterator Pipelines

In idiomatic Rust, standard for loops are often contrasted with iterator adapter chains (.map(), .filter(), .fold()).

  • Use for loops when the operation involves complex early exits across multiple conditions, heavy error handling with ? across nested branches, or imperative mutations of external state.
  • Use iterator pipelines when the transformation is declarative, linear, and maps cleanly to functional operations without side effects.

Because Rust compiles both constructs down to efficient machine code using the same iterator mechanics, performance between a well-written for loop and an iterator chain is generally identical. The choice is guided by maintainability and code clarity.

Leave a Comment