首页 > 解决方案 > Rust if let Optionals 和比较条件

问题描述

我有很多这样的代码,为了清楚起见,我想用"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?
}

不确定将 let 与比较绑定的语法:

if let (Some(a),Some(b) = (maybe_num_A, maybe_num_B) ???&&??? a > b {
   ... 
}

标签: rust

解决方案


如果您只是比较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
}

如果两个值中的任何一个为None,则默认为false


推荐阅读