Rust While Loop

In Rust, loops allows you to run a block of code repeatedly. One of the most common types of loops is the while loop, which runs as long as a given condition is true.

Rust While Loop Syntax #

while condition {
    // code to run repeatedly
}
Code language: Rust (rust)
  • The condition must be a bool (true/false).
  • The block of code runs as long as the condition is true.
  • When the condition becomes false, the loop stops.

In practice, for loops are often cleaner for collections, but while is great for more flexible conditions.

Basic Rust While Loop Example #

The following example illustrates how to use a simple while loop:

fn main() {
    let mut number = 3;

    while number != 0 {
        println!("{number}!");

        number -= 1; // decrease number
    }

    println!("LIFTOFF!!! ๐Ÿš€");
}
Code language: Rust (rust)

Output:

3!
2!
1!
LIFTOFF!!! ๐Ÿš€
Code language: Rust (rust)

Here:

  • The loop runs while number != 0.
  • On each iteration, we print the number and subtract 1.
  • Once number becomes 0, the condition is false โ†’ the loop stops.

Infinite Loop #

If you forget to update the condition, your program might run forever. The following example illustrates a program that runs forever due to the infinite loop:

fn main() {
    let mut x = 5;

    while x > 0 {
        println!("x is {x}");
        // BUG: we forgot to decrease x
    }
}
Code language: Rust (rust)

This loop will never end, because x always stays 5. Therefore, you should always make sure the loop condition can become false.

Using break and continue in a while Loop #

The while loop supports two useful control keywords:

  • break
  • continue

break โ€“ Exit the loop immediately #

fn main() {
    let mut number = 0;

    while number < 10 {
        if number == 5 {
            println!("Reached 5, breaking out of loop.");
            break; // Exit the loop
        }
        println!("number = {}", number);
        number += 1;
    }
}
Code language: Rust (rust)

Output:

number = 0
number = 1
number = 2
number = 3
number = 4
Reached 5, breaking out of loop.
Code language: Rust (rust)

continue โ€“ Skip to the next iteration #

fn main() {
    let mut number = 0;

    while number < 5 {
        number += 1;

        if number == 3 {
            println!("Skipping number 3");
            continue; // Skip printing 3
        }

        println!("number = {}", number);
    }
}
Code language: Rust (rust)

Output:

number = 1
number = 2
Skipping number 3
number = 4
number = 5Code language: Rust (rust)

Summary #

  • A while loop runs as long as its condition is true.
  • Always ensure the condition will eventually become false to avoid infinite loops.
  • You can use while for countdowns, condition-based repetition, or manual iteration.
Was this Helpful ?