Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 717
CoolOppo Avatar asked Sep 14 '25 05:09

CoolOppo


2 Answers

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() { ... }
like image 124
Laney Avatar answered Sep 15 '25 22:09

Laney


If y and x are just intermediary values needed for the computation of u, then this is exactly what .and_then is for:

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

becomes:

if let Some(t) = y.and_then(f) {
    do_thing = false;
} else {
    do_thing = true;
}
like image 33
Stef Avatar answered Sep 15 '25 20:09

Stef