In Rust, the loop keyword is used to create an infinite loop until explicitly exited using the break statement. Unlike loops in other languages, Rust's loop can return a value, making it very flexible when handling repetitive tasks.

Basic Syntax

The syntax of a loop loop is very simple:

loop { 
    /* code block */ 
}

It will continuously execute the code inside the loop body unless you explicitly use the break keyword to exit the loop.

fn main() {
    loop {
        println!("hello world!");
    }
}

This code will infinitely print hello world until you press Ctrl + C to terminate the program;

Controlling the Loop with break and continue

In a loop loop, break is used to immediately exit the loop, while continue is used to skip the remaining part of the current iteration and proceed directly to the next iteration.

fn main() {
    let mut num = 0;
    loop {
        num += 1;
        if num % 2 == 0 {
            continue; // skip even numbers
        }
        println!("Odd number: {}", num);
        if num >= 7 {
            break; // exit the loop when num reaches 7
        }
    }
}

Program Output

Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7

Return Value of loop

Rust's loop loop can return a value, which is achieved by following the break statement with an expression. The return value is assigned to a variable outside the loop. This is very useful when you need to extract a result from the loop.

For example, repeatedly validating user input until a valid number is entered:

fn main() {
    let number: i32 = loop {
        let mut input = String::new();
        println!("Please enter an integer:");

        std::io::stdin()
            .read_line(&mut input)
            .expect("Failed to read input");
        
        let input = input.trim();
        let parsed = input.parse();
        
        if parsed.is_ok(){
            break parsed.unwrap(); // return the number
        }
        
        println!("Your input '{}' is not an integer", input);
        
    };
    
    println!("You entered a number: {}", number);
}

Program Execution Effect

Please enter an integer:
abc
Your input 'abc' is not an integer
Please enter an integer:
3.14
Your input '3.14' is not an integer
Please enter an integer:
123
You entered a number: 123

Loop Labels

Loop labels are used in nested loops to precisely control which loop to break out of, avoiding the limitation of only being able to break out of the innermost loop.

'label_name: loop {
    // ...
    break 'label_name;  // break out of the specified loop
    continue 'label_name;  // jump to the next iteration of the outer loop
}

Usage with return value:

break 'label_name return_value;

Example of breaking out of an outer loop:

'outer: loop {
    println!("Outer loop start");
    
    loop {
        println!("  Inner loop");
        break 'outer;  // directly break out of the outer loop
    }
    
    println!("This line will never execute");
}