I just had a situation similar to the first example in the std::option module docs:
fn divide(numerator: f64, denominator: f64) -> Option<f64> {
if denominator == 0.0 {
None
} else {
Some(numerator / denominator)
}
}
I had a condition, and depending on the condition I either created a None or a Some(value). So I thought, wouldn’t it be nice if I could just call a function on the condition that returns a Some(value) if the condition is met, and a None otherwise. So I wrote up some magical function, to see if it would look weird.
fn divide(numerator: f64, denominator: f64) -> Option<f64> {
(denominator != 0.0).into_option(|| numerator / denominator)
}
I’d like to get some opinions on the readability. Will this create more confusion than it’s worth? Also, it’s not really enough for its own crate, so if there are other suggestions that go along the same lines, a more general crate collecting similar traits and functions might be the right way to go.
##Detailed Implementation:
Fully runnable example in the PlayPen.
trait BoolExt {
fn into_option<T, F>(self, f: F) -> Option<T> where F: Fn() -> T;
}
impl BoolExt for bool {
fn into_option<T, F>(self, f: F) -> Option<T> where F: Fn() -> T {
if self {
Some(f())
} else {
None
}
}
}