Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading