...

/

Replacing For With While

Replacing For With While

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.

Press + to interact
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
...