What is the difference between loop and while true?

前端 未结 4 1217
一向
一向 2021-02-05 02:11

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

4条回答
  •  难免孤独
    2021-02-05 02:55

    The first thing to say is, in terms of performance, these are likely to be identical. While Rust itself doesn't do anything special with while true, LLVM likely does make that optimisation. The Rust compiler tries to keep things simple by delegating optimisations to LLVM where it can.

    in general, the more information we can give to the compiler, the better it can do with safety and code generation

    While certain constant expressions might get optimised away by LLVM, the semantics of the language are not altered by whether an expression is constant or not. This is good, because it helps humans reason about code better too.

    Just because true is a simple expression, we know it's constant. And so is true != false and [0; 1].len() == 1. But what about num_cpus::get() == 1? I actually don't know if there are some compilation targets where that could be constant, and I shouldn't have to think about it either!

    The error in telotortium's example would be more significant when combined with generated code or macros. Imagine a macro which sometimes results in a simple static expression like true == true, but sometimes references a variable or calls a function. Sometimes the compiler is able to ascertain that the loop runs once, but other times it just can't. In Rust right now, the error in that example will always be an error, no matter what code was generated for that condition. No surprises.

提交回复
热议问题