简体   繁体   English

Rust:`while true` 不能编译,但 `loop` 可以

[英]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的控制流更容易被编译器理解:

  • the compiler understands that a loop is executed at least once编译器知道一个loop至少执行一次
  • a loop without a break has type !没有breakloop有类型! (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的值
  • this means the compiler can reason about loop termination (or the lack thereof), if the loop does not contain a break statement it knows that the code following the loop is dead, it can never execute这意味着编译器可以推断循环终止(或缺少循环终止),如果循环不包含break语句,它知道循环后面的代码已死,它永远无法执行

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 truewhile 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.

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