While and for in are not the same?


    let x = 3 ;

// FINE
    let mut r = 0..x ;  
    while r.next().is_some() {
        println!("while works");
    }

// NOT FINE      Q.: WHY ?
    while (0..x).next().is_some() {
        println!("while does not work");
    }

// MEANWHILE EVERYTHING IS FINE
    for _ in 0..x  {
        println!("for works");
    }

You are creating a new iterator for each loop condition check. Since it's the same iterator each time, you get the same result, and thus an infinite loop.

The first example creates a separate iterator, which is polled on each condition check, and thus runs to completion. The third example is essentially equivalent to the first one.

8 Likes

That is correct, while and for are not the same. That is probably why we have both of them :slight_smile:

1 Like

You may be interested in the notional desugaring of for loops.

6 Likes

While loops continuously reevaluate the predicate to see if it is true and if it should then execute the code inside.

For loops, on the other hand, run through an iterator until it reaches the end.

In essence, your second while loop can be rewritten as:

loop {
    let mut r = (0..x);
    if !r.next().is_some() {
        break;
    }
    println!("while does not work");
}

Every time the program goes over the line let mut r = (0..x) it creates a new iterator from 0 to x.
The reason your first while loop works is the it only creates an iterator once, not every time it goes through the loop:

let mut r = 0..x ;
loop {
    if !r.next().is_some() {
        break;
    }
    println!("while works");
}
3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.