rust

How can I "collapse" nested `if let` statements which all run the same code in their `else` clauses?


Here's a simple example:

if let Some(x) = y {
    if let Some(t) = u {
        do_thing = false;
    } else {
        do_thing = true;
    }
} else {
    do_thing = true;
}

I would think that you could just have something like...

if let Some(x) = y && let Some(t) = u {
    do_thing = false;
} else {
    do_thing = true;
}

...but that doesn't seem to work. Is there a clean solution to this?


Solution

  • if let (Some(x), Some(t)) = (y, u) {
        do_thing = false;
    } else {
        do_thing = true;
    }
    

    if you don't need values then you can write

    if y.is_some() && u.is_some() { ... }