Trait safecast::TryCastFrom

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

    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§

Test if value can be cast into Self.

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

Provided Methods§

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

Implementors§