我有这段代码:
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);
}
}
但这不起作用。怎么做?
答案 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);
}
}
fuse
保证在next
返回None
一次后,对next
的每次通话都会给None
。