I often find myself writing something akin to the following:
(boolean_value)
.then(||())
.and_then(|_| produces_an_option())
I know I could just write:
if boolean_value {
produces_an_option()
} else {
None
}
...but for various circumstantial reasons, that if statement often leaves me feeling that the code has grown harder to follow. This is particularly true of longer functions: I tend to forget what the outer return type is midway through writing the inner logic, even after I refactor, simplify, or otherwise break things up!
Using this then...and_then
from the get-go makes it easier for me to keep in mind what I'm doing, and by extension, why I started doing it in the first place.
I discover myself using a similar pattern (with increased frequency) when working with results, although it often becomes more convoluted
(boolean_value)
.then(||())
.ok_or_else(|_| some_error)
.and_then(|()| produces_a_result())
My questions:
Is there a more straightforward (or even just alternative) way to go from a boolean type to one of the Try
-ish types without using an if
expression?
If you encountered code like (boolean_value).then(||()).and_then(|_| stuff )
, would you intuitively recognize the intent or wonder why in tarnation it was written that way?