What is the difference between loop and while true?

前端 未结 4 1216
一向
一向 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

    This was answered on Reddit. As you said, the compiler could special-case while true, but it doesn't. Since it doesn't, the compiler doesn't semantically infer that an undeclared variable that's set inside a while true loop must always be initialized if you break out of the loop, while it does for a loop loop:

    It also helps the compiler reason about the loops, for example

    let x;
    loop { x = 1; break; }
    println!("{}", x)
    

    is perfectly valid, while

    let x;
    while true { x = 1; break; }
    println!("{}", x);
    

    fails to compile with "use of possibly uninitialised variable" pointing to the x in the println. 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 like loop does now. I believe this is what Java does.)

提交回复
热议问题