Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
do-while loops in Rust
while {
let x = foo();
bar(x);
x != 0
} {}
@jrupac
Copy link

jrupac commented Jan 21, 2014

You can do the same trick in C, too:

int x;
while (
  x = foo(),
  bar(x),
  x != 0
) {}

and even weirder, like this (on some compilers):

int x;
while (({
  x = foo();
  bar(x);
  x != 0;
})) {}

@jFransham
Copy link

jFransham commented Jun 15, 2015

This is an ancient thread but I thought I'd share a trick from my first rust project -- it's crazy that this still doesn't exist in stable rust (and I haven't found any mention of it in the nightly book).

macro_rules! run {
    ($x:block until $y:expr) => {{
        while {
            $x;
            !$y
            } {}
    }};
    ($x:block if_still $y:expr) => {{
        while {
            $x;
            $y
            } {}
    }};
}

Additionally, I think keyword! should be parsed seperately to keyword, so you could write this as do! while! without the compiler complaining.

(Should note that I never ended up using this macro because it was too ugly in use, so take from that what you will)

@donbright
Copy link

donbright commented Dec 12, 2018

really helps porting javascript . thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment