Search code examples
rustoption-type

What is the best way to check if the value inside an option inside a result satisfies a condition in rust?


I have a function that returns something like Result<Option<Value>, Error>, and I want to check if there is a value and if it matches a condition. There are two straightforward ways:

if let Ok(Some(value)) = func() {
    if /* condition */ {
        /* do something */
    }
}

and

if func().is_ok_and(|option| option.is_some_and(|value| /* condition */ )) {
    /* do something */
}

The first one seems more readable to me, but in some cases I can imagine a lot of nesting showing up. The second is less readable and introduces extremely long lines, but prevents excessive nesting. Is one preferable over the other? Or is there some other way I'm unaware of that is simpler?

Something similar to what is discussed in this github issue would be very helpful, by doing this:

if let Ok(Some(value)) = func() && /* condition */ {
    /* do something */
}

preventing excessive nesting and staying readable, but I found no equivalent of this that currently exists in rust.


Solution

  • std provides a matches! macro, which you can use (it expands to a match statement, so you can use the if syntax):

    if matches!(func, Ok(Some(value)) if /* condition */) {
        /* do something */
    }
    

    matches! is the best choice when you need a boolean and not a branch, but still works inside an if, too.