The rust loop {}
syntax has a unique feature: it has a return value. Consider this code:
let val = loop {
let random_number = rng::random();
if random_number < 0.5 {
break random_number;
}
}
This will set val to the first random number below 0.5. This wouldn't work for any other kind of loop since they could potentially exit before hitting a break
.
Other languages don't have this because they have statements distinct from expressions, so loops don't return anything. In rust all other loops return ()
This feature was actually added later, initially the loop{}
construct existed as the only way to create a !
"never" type.
#define forever while (1)
and then you can just doforever { ... }
$\endgroup$DO ... LOOP
, although you can also add aWHILE
orUNTIL
condition to either theDO
or theLOOP
. $\endgroup$for { ... }
which is the same asfor ;; { ...}
. $\endgroup$