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:
- https://github.com/rust-lang/rust/issues/62358 (contains).
- https://github.com/rust-lang/rust/pull/87036 (reduce).
Required Methods§
Sourcefn reduce<F: FnOnce(T, T) -> T>(self, other: Option<T>, f: F) -> Option<T> ⓘ
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 areSome(_)
.Some(x)
if either of the options isSome(x)
and the other isNone
.None
if both options areNone
.
§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);
Sourcefn fmt_or_empty(&self) -> OptionFmt<'_, T>
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()));
Sourcefn fmt_or<U: Display>(&self, u: U) -> OptionFmtOr<'_, T, U>
fn fmt_or<U: Display>(&self, u: U) -> OptionFmtOr<'_, T, U>
Sourcefn fmt_or_else<U: Display, F: Fn() -> U>(
&self,
f: F,
) -> OptionFmtOrElse<'_, T, F>
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.