A "for let" similar to "while let"?


#1

Another handy idea could be to support “for let” too:

fn main() {
    use std::io::{BufRead, stdin};
    let stdin = stdin();

    // Current way:
    for line in stdin.lock().lines() {
        if let Some(line) = Some(line) {
            //...
        } else {
            break;
        }
    }

    // New way:
    for let Some(line) = stdin.lock().lines() {
        //...
    }
}

#2

It could be, but in this particular case I can see two other ways to write it that seem more readable to me:

fn main() {
    use std::io::{BufRead, stdin};
    let stdin = stdin();

    for line in stdin.lock().lines().take_while(|line| line.is_ok()) {
        if let Some(line) = Some(line) {
            //...
        }
    }

    let mut lines = stdin.lock().lines();
    while let Some(Ok(line)) = lines.next() {
        //...
    }
}

#3

The first one should look more like this, I think:

for line_result in stdin.lock().lines().take_while(|line| line.is_ok()) {
    let line = line_result.unwrap(); // never fails
    //...
}

#4

For the specific case of options in iterators you can use flat_map to filter out Nones (plaground link), it’s as simple as ...iter().flat_map(|opt| opt).