[英]Rust: `while true` does not compile but `loop`does
I am very new to Rust and to low-level languages in general.我对 Rust 和一般的低级语言非常陌生。 I noticed that in the code below, if I replace
loop
with while true
the code doesn't compile anymore.我注意到在下面的代码中,如果我用
while true
替换loop
,则代码不再编译。 I would actually expect the version with loop
not to compile as well, because the return statement is inside an if statement, so not all code paths would return a value.我实际上希望带有
loop
的版本也不会编译,因为 return 语句在 if 语句中,所以并非所有代码路径都会返回一个值。
pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> {
let mut left = 0;
let mut right = numbers.len() - 1;
loop {
while numbers[left] + numbers[right] > target {
right -= 1;
}
if numbers[left] + numbers[right] == target {
break vec![left as i32 + 1, right as i32 + 1];
} else {
left += 1;
}
}
}
I am also open to suggestions on how to make the code above more Rust idiomatic!我也愿意接受有关如何使上面的代码更符合 Rust 习惯的建议!
That is because loop
's control flow is much better understood by the compiler:这是因为
loop
的控制流更容易被编译器理解:
loop
is executed at least onceloop
至少执行一次loop
without a break
has type !
break
的loop
有类型!
(never), which unifies with all types (in type-system lingo it's a "bottom" type), a loop with a break
has type ()
, a loop with a valued break
has whatever type break
's value has break
的循环具有类型()
,带有值break
的循环具有任何类型break
的值break
statement it knows that the code following the loop is dead, it can never executebreak
语句,它知道循环后面的代码已死,它永远无法执行None of that is the case of a while
loop, there is no special-case for while true
, or while false
, they're not treated any differently than any other while
loop: as far as the compiler is concerned they can all run for 0+ iterations这些都不是
while
循环的情况,对于while true
或while false
没有特殊情况,它们的处理方式与任何其他while
循环没有任何不同:就编译器而言,它们都可以运行0+ 次迭代
Hence:因此:
let mut a;
loop {
a = 1;
break;
}
a
compiles but编译但
let mut a;
while true {
a = 1;
break;
}
a
does not compile.不编译。 That is also why
loop
can have a result value but while
can not.这也是为什么
loop
可以有结果值而while
不能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.