简体   繁体   中英

Why is while not an expression in Rust

I'm new to Rust. It seems to me that a major difference between loop and while is that loop is an expression that returns a value. But why can't while be an expression? Code like this won't compile:

fn main() {
    let mut count = 0;
    let x = while count != 2 {
        count += 1;
        count
    };
    println!("{}", x);
}

But maybe the compiler could interpret the while block like this:

let x = {
    count += 1; // 1st iteration
    count += 1; // 2nd iteration
    count
};

I know this looks semanticly strange. But is this the only reason that loop exist?

I'm aware that while true is not allowd, but you can always do this

let x = 10;
while x != 11 {
    println!("test");
}

which behaves exactly like while true .

But why can't while be an expression?

There have been many discussions about this and at least one RFC. There are many details to resolve. For instance, what do you do when a while does not enter the body the first time?

But is this the only reason that loop exist?

It was the most reasonable one to have first. loop was not always an expression either!

I'm aware that while true is not allowd

It is allowed although the relevant warning is enabled by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM