如何使用Rust迭代器多次`if let`?

时间:2017-02-03 14:25:37

标签: rust

我有这段代码:

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);
        }
    }
}

是否可以有两个if let?我试过了:

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

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

但这不起作用。怎么做?

1 个答案:

答案 0 :(得分:5)

您可以使用“融合”迭代器将多个值收集到元组中,然后使用if let

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保证在next返回None一次后,对next的每次通话都会给None