Rust 如果让/而让
示例
iflet
组合模式match和if语句,并允许进行简短的非详尽匹配。
if let Some(x) = option {
do_something(x);
}这等效于:
match option {
Some(x) => do_something(x),
_ => {},
}这些块也可以具有else语句。
if let Some(x) = option {
do_something(x);
} else {
panic!("option was None");
}此块等效于:
match option {
Some(x) => do_something(x),
None => panic!("option was None"),
}whilelet
组合模式匹配和while循环。
let mut cs = "Hello, world!".chars();
while let Some(x) = cs.next() {
print("{}+", x);
}
println!("");打印H+e+l+l+o+,++w+o+r+l+d+!+。
等效于使用loop{}和match语句:
let mut cs = "Hello, world!".chars();
loop {
match cs.next() {
Some(x) => print("{}+", x),
_ => break,
}
}
println!("");