The Rust tutorial, and now book claim there is a difference between while true
and loop
, but that it isn't super important to understand at this stage.
If you need an infinite loop, you may be tempted to write this:
while true {
However, Rust has a dedicated keyword, loop, to handle this case:
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.
Having done a little bit of compiler-type work, I have to wonder what possible semantic difference there is, since it would be trivial for the compiler to figure out both are an infinite loop.
So, how does the compiler treat them differently?