You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In a decent number of situations, I end up finding myself writing code like:
if foo {Some(bar)}else{None}
This happens especially in closures passed to Iterator::filter_map, but I also frequently find that I want this in .and_then (e.g., on futures). For cases like these, it'd be very handy to have a concise way of turning booleans into Options. For example:
There could also be closure variants of this for cases where the T is expensive to construct, but in my experience those cases are rarer. That would let the code above become:
foo.map_true(bar)
The name could of course be bikeshed (if_true?), but I think this is a pretty versatile and useful shorthand!
Are you looking for Option::filter()? It's currently unstable so you can only use it with #[feature(option_filter)] on nightly, but it seems like it's what you want.
For what it's worth, I've seen this question come up multiple times in the past (and I know I've made use of the pattern before). Perhaps it is worth considering adding it to bool's implementation.
Edit: Ah, I knew I had seen it recently. I forgot it was in the RFCs repository rather than this one.
@ScratchMan544 Option::filter isn't quite the same, as it is Option<T> -> bool -> Option<T>, whereas what I want is bool -> T -> Option<T>. The RFC @kennytm links is exactly this (though I think it should also have a variant for false)! I guess I'll close in favor of that.
Activity
Reconcyl commentedon May 8, 2018
Are you looking for
Option::filter()? It's currently unstable so you can only use it with#[feature(option_filter)]on nightly, but it seems like it's what you want.killercup commentedon May 8, 2018
You could probably use boolinator to write
foo.as_some(bar)varkor commentedon May 8, 2018
For what it's worth, I've seen this question come up multiple times in the past (and I know I've made use of the pattern before). Perhaps it is worth considering adding it to
bool's implementation.Edit: Ah, I knew I had seen it recently. I forgot it was in the RFCs repository rather than this one.
kennytm commentedon May 8, 2018
Please check rust-lang/rfcs#2180.
jonhoo commentedon May 8, 2018
@ScratchMan544
Option::filterisn't quite the same, as it isOption<T> -> bool -> Option<T>, whereas what I want isbool -> T -> Option<T>. The RFC @kennytm links is exactly this (though I think it should also have a variant forfalse)! I guess I'll close in favor of that.