Reputation: 42749
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 let
s? 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
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);
}
}
fuse
guarantees that after next
returns None
once, every call to next
will give None
.
Upvotes: 9