Rust while Loop

In Rust, a while loop is used to define a loop that iterates repeatedly as long as a specified condition is true.

A while loop is defined using syntax that includes a condition. The loop executes as long as the condition remains true:

while <condition> {}

In the following example, the while loop iterates until i reaches 5, incrementing i once with each iteration:

let mut i = 1;

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

Standard Output:

i: 1
i: 2
i: 3
i: 4

In this example, we created a mutable variable named i. We then used the while keyword to create a loop that executes as long as i is less than 5. Since i is initialized with a value of 1, the loop executes four times.

The while keyword creates a type of indefinite loop. This means that the number of iterations is unknown at compile time. Note that this is different from an infinite loop, which can be created using the loop keyword.

In Rust, loop and while loops are both indefinite, but while loops are finite.

Similar to loop, while can use the break and continue keywords to facilitate control flow.

forDefiniteFinite
loopIndefiniteInfinite
whileIndefiniteFinite

Using break in a while Loop

When used in a while loop, the break keyword can be used to terminate the loop. Using break will terminate the loop even if it is located within a conditional expression.

When paired with a conditional, break is a convenient way of supporting control flow by breaking out of the loop when a condition is met. This is why we often encounter break inside a conditional:

while i < 5 {
    println!("i: {}", i);
    i += 1;
    if i == 3 {
        break;
    }
}

Standard Output:

i: 1
i: 2

Using continue in a while Loop

The continue keyword is used to jump to the start of the next loop. Using continue will stop execution of the current loop and start a new iteration of the while loop.

let mut i = 0;

while i < 5 {
    i += 1;
    if i == 3 {
        println!("Number 3");
        continue;
    }
    println!("i: {}", i);
}

Standard Output:

i: 1
i: 2
Number 3
i: 4
i: 5