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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With