What is the difference between loop and while true?

前端 未结 4 1311
一向
一向 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:52

    What is the difference between loop and while true?

    You could ask what is the difference between for and while? The answer will be close to: What is a programming idiom?

    When you write while condition {}, you say "while condition is true, do that", but we can see that say "while true is true, do that", is redundant. This is where loop comes from, it can express infinite loops very well because we say "loop on that". We don't have any condition, this is better.

    So, how does the compiler treat them differently?

    I can't answer the "how" question, but I suppose you want to know "why". It allows the compiler to know that this loop will run at least one time, like the do {} while (condition); from C. The compiler can use this information to produce better code or warnings. Plus, you will be certain that the loop will be executed where a while loop could be gone because the compiler optimize it away. The fun part is that internally Rust uses LLVM, and it looks like LLVM doesn't have a way to express infinite loop, so it produces bugs in some cases.

提交回复
热议问题