148. Result::is_ok_and — Test the Variant and the Value in One Call
Checking “is this Ok, and is the inner value positive?” usually means a match or an if let. Result::is_ok_and collapses both questions into one line.
The pattern crops up everywhere: you have a Result, and you want a bool that says “yes, it succeeded and the value passes some test”. Without help, you write this:
| |
It works, but five lines for what reads as one question is a lot. Result::is_ok_and takes a closure that runs only on the Ok value, and returns false for any Err:
| |
The closure receives the value by move, so it works cleanly with references too:
| |
There’s a mirror method for the failure path. Result::is_err_and runs the predicate only on the Err value:
| |
Both methods short-circuit on the wrong variant without ever calling the closure, so you can put expensive checks in the predicate without worrying about wasted work on the unhappy path.
A nice place this shines is filtering an iterator of Results:
| |
Same trick exists on Option as is_some_and and is_none_or — small surface area, big readability win.