`and_then`-esque fn for `bool`

Currently bool only has two methods, then and then_some. They are essentially the same: then_some takes a T and returns an Option<T> while then takes a FnOnce() -> T and returns an Option<T>. Notably missing however is a function that takes FnOnce -> Option<T> and returns an Option<T>. Admittedly this is a very niche use case, but it seems like std::option::Option does a good job of covering all possible needs, e.g., and_then, flatten, transpose, is_some_and, or, etc. are all very specific, but useful when needed. Currently I'm in a situation where I need to do something like:

(a == b)
   .then(|| text.parse::<f32>().ok())
   .flatten()

Clearly not the worst thing in the world, but still I think it would help to fill out the std library if we could do:

(a == b)
   .then_maybe(|| text.parse::<f32>().ok())
3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.