devela::all

Trait ExtOption

Source
pub trait ExtOption<T>: Sealed {
    // Required methods
    fn contains<U: PartialEq<T>>(&self, x: &U) -> bool;
    fn reduce<F: FnOnce(T, T) -> T>(self, other: Option<T>, f: F) -> Option<T> ;
    fn fmt_or_empty(&self) -> OptionFmt<'_, T>;
    fn fmt_or<U: Display>(&self, u: U) -> OptionFmtOr<'_, T, U>;
    fn fmt_or_else<U: Display, F: Fn() -> U>(
        &self,
        f: F,
    ) -> OptionFmtOrElse<'_, T, F>;
}
Expand description

Extension trait providing additional methods for Option.

This trait is sealed and cannot be implemented for any other type.

See also ExtResult, ExtOptRes.

Based on work from:

Required Methods§

Source

fn contains<U: PartialEq<T>>(&self, x: &U) -> bool

Returns true if the option is a Some value containing the given value.

§Examples
assert_eq!(Some(1).contains(&1), true);
assert_eq!(Some(1).contains(&2), false);
assert_eq!(None::<u8>.contains(&1), false);
Source

fn reduce<F: FnOnce(T, T) -> T>(self, other: Option<T>, f: F) -> Option<T>

Merges self with another Option.

Returns

  • Some(f(l, r)) if both options are Some(_).
  • Some(x) if either of the options is Some(x) and the other is None.
  • None if both options are None.
§Examples
let (x, y) = (Some(2), Some(4));

assert_eq!(x.reduce(y, Add::add), Some(6));
assert_eq!(x.reduce(y, min), Some(2));

assert_eq!(x.reduce(None, Add::add), x);
assert_eq!(None.reduce(y, min), y);

assert_eq!(None.reduce(None, i32::add), None);
Source

fn fmt_or_empty(&self) -> OptionFmt<'_, T>

Format some value, or display an empty string if it’s None.

§Examples
assert_eq!("0x42", format!("{:#x}", Some(0x42).fmt_or_empty()));
assert_eq!("", format!("{:#x}", None::<u8>.fmt_or_empty()));
Source

fn fmt_or<U: Display>(&self, u: U) -> OptionFmtOr<'_, T, U>

Format some value, or an alternative if it’s None.

The alternative value must implement Display regardless of which formatting is used originally.

§Examples
assert_eq!("42", format!("{}", Some(Box::new(42)).fmt_or("Nothing")));
assert_eq!("Nothing", format!("{}", None::<u8>.fmt_or("Nothing")));
Source

fn fmt_or_else<U: Display, F: Fn() -> U>( &self, f: F, ) -> OptionFmtOrElse<'_, T, F>

Format some value, or run an alternative closure if it’s None.

The value returned from the closure must implement Display regardless of which formatting is used originally.

The value returned from the closure is not stored after use. Therefore, using a single OptionFmtOrElse object for multiple formatting operations will run the closure multiple times.

§Examples
assert_eq!("42", format!("{}", Some(42).fmt_or_else(|| "Nothing")));
assert_eq!("Nothing", format!("{}", None::<u8>.fmt_or_else(|| "Nothing")));

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<T> ExtOption<T> for Option<T>