utilz_rs/
option_utils.rs

1/// Extension methods for `Option<T>`.
2pub trait OptionUtils<T> {
3    /// Returns the value inside `Some`, or the fallback if `None`.
4    fn or_default_with(self, fallback: T) -> T;
5
6    /// Executes a closure if the `Option` is `Some`.
7    ///
8    /// Returns the same `Option` back.
9    #[must_use]
10    fn if_some<F: FnOnce(&T)>(self, f: F) -> Option<T>;
11}
12
13impl<T> OptionUtils<T> for Option<T> {
14    fn or_default_with(self, fallback: T) -> T {
15        self.unwrap_or(fallback)
16    }
17
18    fn if_some<F: FnOnce(&T)>(self, f: F) -> Option<T> {
19        if let Some(ref val) = self {
20            f(val);
21        }
22        self
23    }
24}