简而言之,loop
是一个表达式;while true
是一个语句,它们有不同的用例并提供灵活性和表现力。
主要原因是 loop
块是表达式,而 while
块是语句。区分两者并为每种情况设置不同的规则,使编译器能够进行优化而不牺牲安全性。
虽然 loop
和 while true
循环具有相同的行为(可能有类似的优化——每个 while true
循环迭代开始时的条件检查被删除以提高性能),但它们仍然受到 Rust 实现的限制,不能互换使用。
例如,我们可以像这样使用 loop
循环:
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {}", result);
我们可以看到,我们将
loop
表达式的评估结果分配给结果而没有问题。
另一方面,
while
循环是语句,因此我们无法将它们分配给变量等。
使用
while true
循环执行相同操作的代码如下:
let mut counter = 0;
let mut result = 0;
while counter < 10 {
counter += 1;
if counter == 10 {
result = counter * 2;
break;
}
};
println!("The result is {}", result);
如果我们尝试使用
while true
来实现这个简单的算法,就像
loop
一样,会产生以下编译器错误:
let mut counter = 0;
let mut result = while counter < 10 {
counter += 1;
if counter == 10 {
counter * 2;
break
}
};
println!("The result is {}", result);
error[E0277]: `()` doesn't implement `std::fmt::Display`
--> src/main.rs:10:34
|
10 | println!("The result is {}", result);
| ^^^^^^ `()` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `()`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
while true
暗示你可以将true
提取到一个变量中或从函数中返回它,这会导致循环终止。这不是一个好的开发者体验。 - Richiban