Reputation: 354
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
.
Upvotes: 3
Views: 1903
Reputation: 26066
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.
Upvotes: 9