Why this `while-let` loop doesn't terminate?

I used iter().filter() in a while-let loop, and found it never ends. May I know why this situation happens? Thanks very much for you time. I will be very appreciated if anyone could help me :stuck_out_tongue_winking_eye:

fn main() {
    let a = [0i32, 1, 2, 3, 4, 5, 6];

    while let Some(i) = a.iter().filter(|x| *x % 2 == 1).next() {
        println!("{}", i)        
    }
}

https://play.rust-lang.org/?gist=75bd2e3a348ece4f34c641d452d272c4&version=stable&mode=debug&edition=2015

What you're doing now is repeatedly instantiate new iterator over array, filter it, and print its first number. If you run it on your local terminal, you can see it prints 1 constantly.

Maybe this is what you want.

fn main() {
    let a = [0i32, 1, 2, 3, 4, 5, 6];
    let mut iter = a.iter().filter(|&&x| x % 2 == 1);

    while let Some(i) = iter.next() {
        println!("{}", i);
    }
}

But It's usually better to use for loop if possible.

fn main() {
    let a = [0i32, 1, 2, 3, 4, 5, 6];

    for i in a.iter().filter(|&&x| x % 2 == 1) {
        println!("{}", i);
    }
}
4 Likes