Search⌘ K

Replacing For With While

Understand how to replace for loops with while loops and the loop keyword in Rust. Explore how break enables early exit from infinite loops and how to handle iterator values safely.

We'll cover the following...

When introducing for loops, we mentioned that you can always use a while loop instead of a for loop. That’s pretty tricky to do without break. However, with break, it’s much easier. The basic idea is that we want to break as soon as we encounter a None.

Rust 1.40.0
fn main() {
let mut iter = 1..10;
while true {
match iter.next() {
None => break,
Some(x) => println!("{}", x),
}
}
}

Doing this generates a warning:

warning: denote infinite loops with `loop { ... }`
 --> src/main.rs:3:5
...