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
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 theprintln
. 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 likeloop
does now. I believe this is what Java does.)