Loop in Rust

Loops in Rust are a fundamental control structure that allows for the repeated execution of a block of code. Rust provides several types of loops, including the loop, while, and for loops, each serving different purposes and use cases.

The loop Keyword

The loop keyword in Rust creates an infinite loop, which will continue executing until explicitly told to stop using the break statement. This can be useful for scenarios where you want to keep running a block of code until a certain condition is met.

Basic Loop with Break

Here is a simple example of a loop that increments a counter and breaks when the counter reaches 5:

fn main() {
    let mut counter = 0;                           #1
    loop {
        counter +=1;                               #2
        println!("The counter is now: {counter}");
        if counter == 5 {                          #3
            break;
        }
    }
}
#1 Sets a counter to 0
#2 Increases the counter by 1
#3 Stops when counter == 5

In this example, the loop will print the value of the counter and increment it by 1 on each iteration. Once the counter reaches 5, the break statement is executed, terminating the loop.

Infinite Loop

A loop without a break statement will run indefinitely, as shown in the following example:

fn main() {
    loop {}
}

This loop will continue forever unless interrupted, which is generally not useful unless you have a specific reason to run an infinite loop.

Named Loops

Rust allows you to name loops, which is particularly useful when dealing with nested loops. You can use a tick (') followed by a colon to name a loop. This feature helps in breaking out of specific loops when needed.

Example of Named Loops

fn main() {
    let mut counter = 0;
    let mut counter2 = 0;
    println!("Now entering the first loop.");
 
    'first_loop: loop {                                              #1
        counter += 1;
        println!("The counter is now: {}", counter);
        if counter > 5 {
            println!("Now entering the second loop.");
 
            'second_loop: loop {                                     #2
                println!("The second counter is now: {}", counter2); #3
                counter2 += 1;
                if counter2 == 3 {
                    break 'first_loop;                               #4
                }
            }
        }
    }
}
#1 Gives the first loop a name
#2 Starts a second loop inside the first loop
#3 Now, we are inside 'second_loop.
#4 Breaks out of 'first_loop so we can exit the program

In this example, the program enters the first loop and increments the counter. Once the counter exceeds 5, it enters the second loop. The second loop increments counter2 and breaks out of the first_loop when counter2 reaches 3. This allows the program to terminate gracefully.

Output

Now entering the first loop.
The counter is now: 1
The counter is now: 2
The counter is now: 3
The counter is now: 4
The counter is now: 5
The counter is now: 6
Now entering the second loop.
The second counter is now: 0
The second counter is now: 1
The second counter is now: 2

Returning Values from Loops

Rust also allows you to return a value from a loop using the break statement. This is done by placing the value you want to return immediately after break.

Example of Returning a Value

fn main() {
    let mut counter = 5;
    let my_number = loop {
        counter +=1;
        if counter % 53 == 3 {
            break counter;
        }
    };
    println!("{my_number}");
}

In this example, the loop increments the counter until it finds a value that, when divided by 53, leaves a remainder of 3. The break counter; statement exits the loop and returns the value of counter, which is then assigned to my_number. The program prints 56, as this is the first value that satisfies the condition.