← Back to Rust Course | Chapter 3: Control Flow | Lesson 2 of 7

The loop Keyword

loop makes your program repeat something forever, until you tell it to stop.
Syntax
rust
loop {
    // body
    if condition {
        break;
    }
}

A Basic Infinite Loop

The loop keyword repeats its block forever until a break statement explicitly exits it. This is useful when you don't know ahead of time how many iterations you need.

Example: A Basic Infinite Loop

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `count`, initialized to `0`
    let mut count = 0;
    // Loop forever until an explicit `break`
    loop {
        count += 1;
        // Print "count = {}" to the console, substituting in `count` (with a trailing newline)
        println!("count = {}", count);
        // Check whether `count == 3`
        if count == 3 {
            break;
        }
    }
}

Returning a Value from loop

Unlike most looping constructs, loop is an expression: you can pass a value to break, and that becomes the value the whole loop expression evaluates to.

Example: Returning a Value from loop

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `counter`, initialized to `0`
    let mut counter = 0;
    // Declare an immutable variable `result`; its value comes from the block below
    let result = loop {
        counter += 1;
        // Check whether `counter == 5`
        if counter == 5 {
            break counter * 2;
        }
    };
    // Print "result = {}" to the console, substituting in `result` (with a trailing newline)
    println!("result = {}", result);
}

Labeled Loops

When loops are nested, you can label the outer one with a name like 'outer: and use that label with break or continue to control the outer loop directly from inside the inner one.

Example: Labeled Loops

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `total`, initialized to `0`
    let mut total = 0;
    'outer: loop {
        // Declare a mutable variable `inner_count`, initialized to `0`
        let mut inner_count = 0;
        // Loop forever until an explicit `break`
        loop {
            total += 1;
            inner_count += 1;
            // Check whether `inner_count == 2`
            if inner_count == 2 {
                break;
            }
            // Check whether `total >= 6`
            if total >= 6 {
                break 'outer;
            }
        }
        // Check whether `total >= 6`
        if total >= 6 {
            break;
        }
    }
    // Print "total = {}" to the console, substituting in `total` (with a trailing newline)
    println!("total = {}", total);
}

loop for Retry Logic

A common real-world use of loop is retrying an operation until it succeeds, checking a condition somewhere inside the body rather than only at the top.

Example: loop for Retry Logic

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `attempts`, initialized to `0`
    let mut attempts = 0;
    // Declare an immutable variable `success`; its value comes from the block below
    let success = loop {
        attempts += 1;
        // Check whether `attempts == 3`
        if attempts == 3 {
            break true;
        }
    };
    // Print "Succeeded after {} attempts: {}" to the console, substituting in `attempts, success` (with a trailing newline)
    println!("Succeeded after {} attempts: {}", attempts, success);
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing an infinite loop and forgetting a break condition, causing the program to hang forever.
  2. Not realizing loop can return a value via break value;, and manually tracking a result variable instead.
  3. Confusing loop (always repeats) with while (repeats only while a condition holds).
Chapter Summary
  • loop repeats a block of code indefinitely until a break statement is reached.
  • break value; can exit a loop while also producing a value the loop expression evaluates to.
  • Loop labels ('outer: loop { ... }) let break/continue target a specific outer loop.
  • loop is often used for retry logic or when the exit condition is checked in the middle of the body.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.