Rust also has a while
`while` loop. It looks like this:
let mut x = 5; // mut x: i32 let mut done = false; // mut done: bool while !done { x += x - 3; println!("{}", x); if x % 5 == 0 { done = true; } }
while
`while` loops are the correct choice when you’re not sure how many times
you need to loop.
If you need an infinite loop, you may be tempted to write this:
fn main() { while true { }while true {
However, Rust has a dedicated keyword, loop
`loop`, to handle this case:
loop {
Rust’s control-flow analysis treats this construct differently than a while true
`while
true, since we know that it will always loop. In general, the more information we can give to the compiler, the better it can do with safety and code generation, so you should always prefer
`, since we know that it will always loop. In general, the more information
we can give to the compiler, the better it can do with safety and code
generation, so you should always prefer loop
`loop` when you plan to loop
infinitely.
Let’s take a look at that while
`while` loop we had earlier:
let mut x = 5; let mut done = false; while !done { x += x - 3; println!("{}", x); if x % 5 == 0 { done = true; } }
We had to keep a dedicated mut
`mutboolean variable binding,
` boolean variable binding, done
`done, to know when we should exit out of the loop. Rust has two keywords to help us with modifying iteration:
`, to know
when we should exit out of the loop. Rust has two keywords to help us with
modifying iteration: break
`breakand
` and continue
`continue`.
In this case, we can write the loop in a better way with break
`break`:
let mut x = 5; loop { x += x - 3; println!("{}", x); if x % 5 == 0 { break; } }
We now loop forever with loop
`loopand use
` and use break
`break` to break out early.
continue
`continue` is similar, but instead of ending the loop, goes to the next
iteration. This will only print the odd numbers:
for x in 0..10 { if x % 2 == 0 { continue; } println!("{}", x); }
Both continue
`continueand
` and break
`breakare valid in both
` are valid in both while
`whileloops and [
` loops and for
`for` loops.