Trait safecast::TryCastFrom [−][src]
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
fn can_cast_from(value: &T) -> bool
fn can_cast_from(value: &T) -> bool
Test if value
can be cast into Self
.
fn opt_cast_from(value: T) -> Option<Self>
fn opt_cast_from(value: T) -> Option<Self>
Returns Some(Self)
if the source value can be cast into Self
, otherwise None
.
Provided methods
fn try_cast_from<Err, OnErr: FnOnce(&T) -> Err>(
value: T,
on_err: OnErr
) -> Result<Self, Err>
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
.