Trait safecast::TryCastFrom

source ·
pub trait TryCastFrom<T>: Sized {
    // Required methods
    fn can_cast_from(value: &T) -> bool;
    fn opt_cast_from(value: T) -> Option<Self>;

    // Provided method
    fn try_cast_from<Err, OnErr: FnOnce(&T) -> Err>(
        value: T,
        on_err: OnErr
    ) -> Result<Self, Err> { ... }
}
Expand description

Trait for defining a cast operation when the source type cannot always be cast to the destination type. Defines a can_cast_from method which borrows the source value, allowing for pattern matching without moving the value. When can_cast_from returns true, calling opt_cast_from must return Some(...), otherwise try_cast_from may panic.

Analogous to TryFrom. The inverse of TryCastInto. Prefer implementing TryCastFrom over TryCastInto because implementing TryCastFrom automatically provides an implementation of TryCastInto.

Required Methods§

source

fn can_cast_from(value: &T) -> bool

Test if value can be cast into Self.

source

fn opt_cast_from(value: T) -> Option<Self>

Returns Some(Self) if the source value can be cast into Self, otherwise None.

Provided Methods§

source

fn try_cast_from<Err, OnErr: FnOnce(&T) -> Err>( value: T, on_err: OnErr ) -> Result<Self, Err>

Returns Ok(Self) if the source value can be cast into Self, otherwise calls on_err.

Object Safety§

This trait is not object safe.

Implementors§

source§

impl<F, T: CastFrom<F>> TryCastFrom<F> for T