While loop allows you to execute statements based on conditional value. Rust language provides the following Only one kind while loops.

  • Rust While Loop

Rust Do While Loop is not supported.

Rust While Loop example

It executes the code statement multiple times based on the bool value.

Here is the syntax of a while loop.

while conditional expression{
  //statements
}

while is a keyword in Rust that can not be used as a variable name in a Rust.

conditional-expression is rust expression evaluated to true or false only. if it is true, Statements inside a while loop are executed.

code block contains a single line or block(multiple lines) of code. code block must be enclosed in {} Here are while loop examples in rust.

fn main() {
    let mut number = 20;
    let mut sum = 0;

    while number >= 1 {
        sum = sum + number;
        number = number - 1;
    }
    println!("The Sum is {sum}");
}

Output:

The Sum is 210

Rust Do While Loop example

Do While is to execute multiple blocks of code based on conditional expression value. Rust does not support do while loop, Instead you can do different ways.

Do While Loop is similar to while loop except that checking condition expression is inside the code block. That means code statements are executed at least once.

Here is an example code for the do-while loop in Rust.

fn main() {
    let mut number = 20;
    let mut sum = 0;
    while {
     sum = sum + number;
        number = number - 1;
        if number === 0 {
            break  ;
        }
    }  {}
    println!("The Sum is {sum}");
}