What Is Rust Loop Keyword?

“Loop” is also a keyword in Rust programming, and it’s used to create an infinite loop in the program. Other language uses a “while true” and more methods to create an infinite loop.

“while true” is a specific condition, not a keyword, but Rust provides a dedicated keyword for this.

1) Use “for loop” when you already know how many times to repeat something. For example:

for i in 0..5 {
println!("{}", i);
}

You know it will run 5 times (from 0 to 4).

2) Use a “while loop” when you want to keep doing something as long as a condition is true. For example: “Keep printing until the number is less than 5”

let mut i = 0;
while i < 5 {
println!("{}", i);
i += 1;
}

3) Use “Loop” when you don’t know how many times the code will run. It repeats again and again until you manually tell it to stop.

For example: “Ask the user for input again and again”

loop {
println!("Enter your name:");
// break if user enters something valid
break;
}

It gives you full control. You can exit using break anywhere you want.

If you don’t know control flow and loops? so first learn here: Control Flow and Loop in Rust.

Example: User Login Attempts System

Here, we will create a loop for login attempts that will automatically failed after three attempts.

fn main() {
let correct_password = "rustacean123";
let mut attempts = 0;

loop {
println!("Enter password:");

let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
let input = input.trim();

if input == correct_password {
println!("Access granted.");
break;
} else {
attempts += 1;
println!("Wrong password. Attempt {} of 3", attempts);
}

if attempts == 3 {
println!("Too many failed attempts. Exiting...");
break;
}
}
}

This method is used in real-world applications where a loop handles repeated inputs until success or a limit is reached.

What Are Nested Loops and Loop Labels in Rust?

When you use one loop inside another, it’s called a nested loop. Rust provides the Loop labels feature, which helps you break out of a specific loop, especially useful when you have multiple loops in your program.

Simple example:

fn main() {
let mut outer = 0;

'main_loop: loop {
println!("Outer loop count: {}", outer);

let mut inner = 0;

loop {
println!(" Inner loop count: {}", inner);

if inner == 2 {
break; // this only breaks the inner loop
}

if outer == 2 {
break 'main_loop; // this breaks the outer loop
}

inner += 1;
}

outer += 1;
}
}
  • main_loop is the label name of the outer loop.
  • “break ‘main_loop;” tells Rust “Stop the outer loop right now, no matter where I am.”
  • Without labels, you can only break the innermost loop.
  • With labels, you can control which loop to exit.

Rust gives you a label to jump out of cleanly from a loop.

How to Use loop with return in Rust?

Rust loop is not just for repeating code; it can also return a value! you can use a break value inside a loop to exit the loop and return a result.

Let’s see the example:

fn find_even_number() -> i32 {
let mut number = 1;

let result = loop {
if number % 2 == 0 && number > 10 {
break number; // Exit loop and return 'number' as the result
}
number += 1;
};

result
}

Output:

fn main() {
let even = find_even_number();
println!("Found even number: {}", even);
}

It prints this:

Found even number: 12

Explanations of this code:

  • First, the function keeps increasing the number from 1.
  • Then it checks: Is the number even AND greater than 10?
  • When it finds such a number, it uses “break number;” to exit the loop and return that number as the value of the loop.

Your Exercise: Build a Menu-Based App

Task:
Create a program that do the following terms:

  • Uses a loop to show a menu repeatedly
  • Allow users to choose from options (1. Say Hi, 2. Get Time, 3. Exit)
  • Uses if and match statements to handle choices
  • Breaks the loop if the user chooses option 3

This exercise will help in the real-world use of the loop keyword.

Leave a Comment