Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 907
Boiethios Avatar asked Feb 03 '17 14:02

Boiethios


1 Answers

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.

like image 196
musicmatze Avatar answered Nov 15 '22 10:11

musicmatze