Trait mz_ore::option::OptionExt

source ·
pub trait OptionExt<T> {
    // Required methods
    fn owned(&self) -> Option<<<T as Deref>::Target as ToOwned>::Owned>
       where T: Deref,
             T::Target: ToOwned;
    fn display_or<D>(self, default: D) -> Either<T, D>
       where T: Display,
             D: Display;
    fn display_or_else<D, R>(self, default: D) -> Either<T, R>
       where T: Display,
             D: FnOnce() -> R,
             R: Display;
}
Expand description

Extension methods for std::option::Option.

Required Methods§

source

fn owned(&self) -> Option<<<T as Deref>::Target as ToOwned>::Owned>
where T: Deref, T::Target: ToOwned,

Converts from Option<&T> to Option<T::Owned> when T implements ToOwned.

The canonical use case is converting from an Option<&str> to an Option<String>.

The name is symmetric with Option::cloned.

source

fn display_or<D>(self, default: D) -> Either<T, D>
where T: Display, D: Display,

Returns a type that displays the option’s value if it is present, or the provided default otherwise.

§Examples
use mz_ore::option::OptionExt;

fn render(number: Option<i32>) -> String {
    format!("Your lucky number is {}.", number.display_or("unknown"))
}

assert_eq!(render(Some(42)), "Your lucky number is 42.");
assert_eq!(render(None), "Your lucky number is unknown.");
source

fn display_or_else<D, R>(self, default: D) -> Either<T, R>
where T: Display, D: FnOnce() -> R, R: Display,

Like OptionExt::display_or, but the default value is computed only if the option is None.

§Examples
use mz_ore::option::OptionExt;

fn render(number: Option<i32>, guess: i32) -> String {
    format!(
        "Your lucky number is {}.",
        number.display_or_else(|| format!("unknown (best guess: {})", guess)),
    )
}

assert_eq!(render(Some(42), 7), "Your lucky number is 42.");
assert_eq!(render(None, 7), "Your lucky number is unknown (best guess: 7).");

Object Safety§

This trait is not object safe.

Implementations on Foreign Types§

source§

impl<T> OptionExt<T> for Option<T>

source§

fn owned(&self) -> Option<<<T as Deref>::Target as ToOwned>::Owned>
where T: Deref, T::Target: ToOwned,

source§

fn display_or<D>(self, default: D) -> Either<T, D>
where T: Display, D: Display,

source§

fn display_or_else<D, R>(self, default: D) -> Either<T, R>
where T: Display, D: FnOnce() -> R, R: Display,

Implementors§