pub trait StrictAs {
// Required method
fn strict_as<Dst>(self) -> Dst
where Self: StrictCast<Dst>;
}Expand description
Used to cast values, panicking if the value does not fit.
This is a convenience trait to enable writing
src.strict_as::<Dst>().
This would not work with the
StrictCast::strict_cast
method because the StrictCast trait is generic while its
StrictCast::strict_cast method is not generic.
This trait’s method is suitable for chaining.
If there is an implementation of
StrictCast<Dst> for &Src
but not for Src, and the variable src is of type Src, then
src.strict_as::<Dst>()
would not work and
(&src).strict_as::<Dst>()
is not easy to use with chaining, but
src.borrow().strict_as::<Dst>()
works.
§Panics
This trait’s method panics if the value does not fit in the destination, even when debug assertions are not enabled.
§Examples
use az::StrictAs;
assert_eq!(5i32.strict_as::<u32>(), 5);
assert_eq!(17.1f32.strict_as::<u8>(), 17);The following panics because of overflow.
use az::StrictAs;
let _overflow = (-5i32).strict_as::<u32>();The following example shows how this trait can be used when
StrictCast is implemented for a reference type.
use az::{StrictAs, StrictCast};
use core::borrow::Borrow;
struct I(i32);
impl StrictCast<i64> for &'_ I {
fn strict_cast(self) -> i64 { self.0.strict_cast() }
}
let r = &I(-5);
assert_eq!(r.strict_as::<i64>(), -5);
let owned = I(12);
assert_eq!(owned.borrow().strict_as::<i64>(), 12);Required Methods§
Sourcefn strict_as<Dst>(self) -> Dstwhere
Self: StrictCast<Dst>,
fn strict_as<Dst>(self) -> Dstwhere
Self: StrictCast<Dst>,
Casts the value.
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.