Do while in rust language

how to programming do while() loop like in c and c++ in rust language

The idiomatic equivalent is:

loop {
    do_stuff();
    if !condition {
        break;
    }
}

The “cute” or “terrible” equivalent (depending on your outlook) is:

while {
    do_stuff();
    condition
} {}
15 Likes

A big caveat of that cute/terrible form is that you can't break or continue in that position, but if you really want you can still arrange the corresponding condition false or true.

4 Likes

while(true)
{
expression
if condition
{
break;
}
}

The only way to have a do loop that supports continue on its first iteration (to goto to a classic while loop), is with an explicit variable to track the first iteration of the loop:

macro_rules! do_loop {(
    $body:block while $cond:expr
) => ({
    let mut first = true;
    while ::core::mem::replace(&mut first, false) || $cond
        $body
})}

let mut x = 6;
do_loop!({
    if x == 6 {
        x = 0;
        continue;
    }
    x += 1;
    println!("{}", x);
} while x < 6);

The only remaining issue is that something like

let mut y; // if this were `let mut y = 0` then all would be fine
let mut x = 0;
do_loop!({
    y = x * x;
    x += 1;
    println!("{}", x);
} while x > y);

fails because Rust assumes y may not have been initialized; but this is normal because if there was a continue before the y = ...; line then indeed y would not be initialized.

If do { ... } while ... ; loops were primary language constructs, then trivial cases such as this continue-less example could be handled, but it seems to be a minor win that isn't worth the effort..

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.