This article explains loop keyword usage and examples.

Rust provides the below types to iterate the n number iterations.

  • For loop
  • while loop
  • Loop

Rust loop

the loop is a keyword to iterate infinite times and execute code statements inside a loop.

here is a syntax

loop {
// Code Statements
}

It iterates infinite times and executes code block inside {}.

Here is an example to print messages with indefinite times.

fn main() {
    loop {
    // Print string to the console
    println!("Message");
    }
}

Print the message to the console infinite times.

use CTRL + C to break from the program execution.

We can also use the below keywords

break: used to exit from the loop continue: used to skip the current execution and continue execution from starting.

loop with break

This example explains the usage of the break keyword in the loop.

Here is an example of rust loop break

fn main() {
    let mut number = 0;
    loop {
        number += 1;
        if number == 3 {
            println!("print continue statement");

            continue;
        }
        println!("{}", number);
        if number == 5 {
            println!("Matched and exit from the loop");
            break; // Exit this loop
        }
    }
}

1
2
3
4
5
Matched and exist from the loop

loop keyword with continue

This example explains the usage of the continue keyword in the loop.

In this example, the number is printed on to console. used continue statement that skips the statements after continue inside a loop

fn main() {
    let mut number = 0;
    loop {
        number += 1;
        if number == 3 {
            println!("print continue statement, skipped printing the number");
            continue;
        }
        println!("{}", number);
        if number == 5 {
            println!("Matched and exit from the loop");
            break; // Exit this loop
        }
    }
}

Output:

1
2
print continue statement
4
5
Matched and exit from the loop