What is the difference between loop and while true?

One major difference is that loop can return a value by passing a value to break. while and for will not:

fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    assert_eq!(result, 20);
}

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.)

Tags:

Loops

Rust