Trait az::UnwrappedAs

source ·
pub trait UnwrappedAs {
    // Required method
    fn unwrapped_as<Dst>(self) -> Dst
       where Self: UnwrappedCast<Dst>;
}
Expand description

Used to cast values, panicking if the value does not fit.

This is a convenience trait to enable writing src.unwrapped_as::<Dst>(). This would not work with the UnwrappedCast::unwrapped_cast method because the UnwrappedCast trait is generic while its UnwrappedCast::unwrapped_cast method is not generic.

This trait’s method is suitable for chaining.

If there is an implementation of UnwrappedCast<Dst> for &Src but not for Src, and the variable src is of type Src, then src.unwrapped_as::<Dst>() would not work and (&src).unwrapped_as::<Dst>() is not easy to use with chaining, but src.borrow().unwrapped_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::UnwrappedAs;
assert_eq!(5i32.unwrapped_as::<u32>(), 5);
assert_eq!(17.1f32.unwrapped_as::<u8>(), 17);

The following panics because of overflow.

use az::UnwrappedAs;
let _overflow = (-5i32).unwrapped_as::<u32>();

The following example shows how this trait can be used when UnwrappedCast is implemented for a reference type.

use az::{UnwrappedAs, UnwrappedCast};
use core::borrow::Borrow;
struct I(i32);
impl UnwrappedCast<i64> for &'_ I {
    fn unwrapped_cast(self) -> i64 { self.0.unwrapped_cast() }
}

let r = &I(-5);
assert_eq!(r.unwrapped_as::<i64>(), -5);
let owned = I(12);
assert_eq!(owned.borrow().unwrapped_as::<i64>(), 12);

Required Methods§

source

fn unwrapped_as<Dst>(self) -> Dst
where Self: UnwrappedCast<Dst>,

Casts the value.

Object Safety§

This trait is not object safe.

Implementors§

source§

impl<T> UnwrappedAs for T