How to use if let statement with conditions?

I know it’s possible to express AND logic between if let statement and a condition like this

if let (Some(a), true) = (b, c == d) {
    // do something
}

But what if I need an OR logic?

if let (Some(a)) = b /* || c == d */ {
    // do something
} else {
    // do something else
}

The only way I figure it out is as follows, but I think it’s a little bit ugly as I have to write some code twice

if let (Some(a)) = b {
    // do something
} else if c == d {
    // do something
} else {
    // do something else
}

>Solution :

If you have the same "do something" code in both cases then it must not use a. In that case you can use is_some:

if b.is_some() || c == d {
    // do something
} else {
    // do something else
}

Or in the more general case, you can use matches! to check if b matches a pattern without creating any bindings:

if matches!(b, Some(_)) || c == d {
    // do something
} else {
    // do something else
}

Leave a Reply