What is the difference between loop and while true?
Rust教程(现在预订)声称
If you need an infinite loop, you may be tempted to write this:
1 while true {However, Rust has a dedicated keyword, loop, to handle this case:
1 loop {Rust's control-flow analysis treats this construct differently than a while true, since we know that it will always loop. The details of what that means aren't super important to understand at this stage, but in general, the more information we can give to the compiler, the better it can do with safety and code generation, so you should always prefer loop when you plan to loop infinitely.
在完成了一些编译器类型的工作之后,我不得不想知道在语义上可能存在什么差异,因为对于编译器而言,找出两者都是无限循环将是微不足道的。
那么,编译器如何区别对待它们?
这在Reddit上得到了回答。如您所说,编译器可以对
It also helps the compiler reason about the loops, for example
1
2
3 let x;
loop { x = 1; break; }
println!("{}", x)is perfectly valid, while
1
2
3 let x;
while true { x = 1; break; }
println!("{}", x);fails to compile with"use of possibly uninitialised variable" pointing to the
x in theprintln . In the second case, the compiler is not detecting that the body of the loop will always run at least once.(Of course, we could special case the construct
while true to act likeloop does now. I believe this is what Java does.)
首先要说的是,就性能而言,它们可能是相同的。尽管Rust本身对
in general, the more information we can give to the compiler, the better it can do with safety and code generation
尽管LLVM可能会优化某些常量表达式,但表达式的常量与否不会改变语言的语义。这很好,因为它也可以帮助人们更好地推理代码。
仅仅因为
当与生成的代码或宏结合使用时,telotortium的示例中的错误将更加严重。想象一下一个宏,它有时会导致一个简单的静态表达式,例如
一个主要区别是
1 2 3 4 5 6 7 8 9 10 11 12 13 | fn main() { let mut counter = 0; let result = loop { counter += 1; if counter == 10 { break counter * 2; } }; assert_eq!(result, 20); } |
What is the difference between loop and while true?
您可能会问
当您编写
So, how does the compiler treat them differently?
我无法回答"如何"的问题,但我想您想知道"为什么"。它使编译器知道该循环将至少运行一次,如C中的