Avba
Avba

Reputation: 15296

Rust if let Optionals and compare conditions

I have a lot of code like this, and would like to replace with a "if let" binding for clarity in my case

// 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?
}

Not sure on the syntax to bind the let with a comparison:

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

Upvotes: 5

Views: 2090

Answers (2)

Jason
Jason

Reputation: 5575

If you're only comparing A and B and do not necessarily need to bind them, you could use the .zip method that's in Rust 1.46 and apply a map_or on it, e.g:

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
}

If either of the two values is None, it will default to false.

Upvotes: 4

Peter Hall
Peter Hall

Reputation: 58885

Not sure on the syntax to bind the let with a comparison:

Unfortunately there isn't any. If you need to access bindings from the pattern, you have to do it the old fashioned way:

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

If you don't need the bindings from the pattern then Jason's answer will do the job and might end up cleaner, as long as the actual patterns are relatively simple.

Upvotes: 3

Related Questions