我有很多这样的代码,"if let"为了清楚起见,我想用绑定替换我的情况
// contrived
fn maybe() -> Option<i32> { Some(1)}
let maybe_num_A = maybe();
let maybe_num_B = maybe();
...
match (maybe_num_A, maybe_num_B) {
(Some(a) , Some(b)) if a > b => {
....
}
_ => {} // don't care many times about the other matches that doesn't hold. how to get rid of this?
}
Run Code Online (Sandbox Code Playgroud)
不确定将 let 与比较绑定的语法:
if let (Some(a),Some(b) = (maybe_num_A, maybe_num_B) ???&&??? a > b {
...
}
Run Code Online (Sandbox Code Playgroud)
如果您只是比较A和 ,B并且不一定需要绑定它们,您可以使用Rust 1.46.zip中的方法并对其应用 a ,例如:map_or
let a: Option<i32> = Some(42);
let b: Option<i32> = Some(-42);
if a.zip(b).map_or(false, |(a, b)| a > b) {
// 42 is greater than -42
}
Run Code Online (Sandbox Code Playgroud)
如果两个值中有一个是None,则默认为false。