Closed
Description
I found that defining the following made my code cleaner and shorter, something along these lins would be welcome in the standard library:
/// More operations for options.
pub trait WhenOption<T> {
/// Call a function that borrows the value, if there is one.
fn when_some(&self, action: &fn(&T));
/// Call a function that borrows the mutable value, if there is one.
fn mut_when_some(&mut self, action: &fn(&mut T));
/// Call a function that takes the value, if there is one.
fn take_some(self, action: &fn(T));
/// Call a function that borrows the value, if there is one; otherwise
/// return a default.
fn when_some_or<U>(&self, default: U, action: &fn(&T) -> U) -> U;
/// Call a function that borrows the mutable value, if there is one;
/// otherwise return a default.
fn mut_when_some_or<U>(&mut self, default: U, action: &fn(&mut T) -> U) -> U;
/// Call a function that takes the value, if there is one; otherwise
/// return a default.
fn take_some_or<U>(self, default: U, action: &fn(T) -> U) -> U;
/// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
fn when_map<U>(&self, f: &fn(&T) -> U) -> Option<U>;
}
/// More operations for options.
impl<T> WhenOption<T> for Option<T> {
/// Call a function that borrows the value, if there is one.
fn when_some(&self, action: &fn(&T)) {
match self {
&None => (),
&Some(ref value) => action(value),
}
}
/// Call a function that borrows the mutable value, if there is one.
fn mut_when_some(&mut self, action: &fn(&mut T)) {
match self {
&None => (),
&Some(ref mut value) => action(value),
}
}
/// Call a function that takes the value, if there is one.
fn take_some(self, action: &fn(T)) {
match self {
None => (),
Some(value) => action(value),
}
}
/// Call a function that borrows the value, if there is one; otherwise
/// return a default.
fn when_some_or<U>(&self, default: U, action: &fn(&T) -> U) -> U {
match self {
&None => default,
&Some(ref value) => action(value),
}
}
/// Call a function that borrows the mutable value, if there is one;
/// otherwise return a default.
fn mut_when_some_or<U>(&mut self, default: U, action: &fn(&mut T) -> U) -> U {
match self {
&None => default,
&Some(ref mut value) => action(value),
}
}
/// Call a function that takes the value, if there is one; otherwise
/// return a default.
fn take_some_or<U>(self, default: U, action: &fn(T) -> U) -> U {
match self {
None => default,
Some(value) => action(value),
}
}
/// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
fn when_map<U>(&self, f: &fn(&T) -> U) -> Option<U> {
match self {
&Some(ref value) => Some(f(value)),
&None => None,
}
}
}
Metadata
Metadata
Assignees
Labels
No labels