Boiethios
Boiethios

Reputation: 42749

How to have multiple `if let` with a Rust iterator?

I have this code:

fn main() {
    let mut args = std::env::args();

    if let Some(name) = args.next() {
        if let Some(first) = args.next() {
            println!("One arg provided to {}: {}", name, first);
        }
    }
}

Is it possible to have two if lets? I tried:

fn main() {
    if let Some(name) = args.next() && Some(first) = args.next() {
        println!("one arg provided to {}: {}", name, first);
    }
}

and

fn main() {
    if let Some(name) = args.next() && let Some(first) = args.next() {
        println!("one arg provided to {}: {}", name, first);
    }
}

But this does not work. How to do this?

Upvotes: 6

Views: 1581

Answers (1)

musicmatze
musicmatze

Reputation: 4288

You can use a “fused” iterator to collect multiple values into a tuple and use if let with that:

fn main() {
    let mut args = std::env::args().fuse();
    if let (Some(a), Some(b)) = (args.next(), args.next()) {
        println!("{}, {}", a, b);
    }
}

(Example on the playground)

fuse guarantees that after next returns None once, every call to next will give None.

Upvotes: 9

Related Questions