pub trait CheckedAs {
    fn checked_as<Dst>(self) -> Option<Dst>
    where
        Self: CheckedCast<Dst>
; }
Expand description

Used for checked casts.

This trait’s method returns None if the value does not fit.

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

This trait’s method is suitable for chaining.

If there is an implementation of CheckedCast<Dst> for &Src but not for Src, and the variable src is of type Src, then src.checked_as::<Dst>() would not work and (&src).checked_as::<Dst>() is not easy to use with chaining, but src.borrow().checked_as::<Dst>() works.

Examples

use az::CheckedAs;
use core::f32;

assert_eq!(5i32.checked_as::<u32>(), Some(5));
assert_eq!((-5i32).checked_as::<u32>(), None);
assert_eq!(17.1f32.checked_as::<u8>(), Some(17));
assert_eq!(f32::NAN.checked_as::<u8>(), None);

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

use az::{CheckedAs, CheckedCast};
use core::borrow::Borrow;
struct I(i32);
impl CheckedCast<u32> for &'_ I {
    fn checked_cast(self) -> Option<u32> { self.0.checked_cast() }
}

let r = &I(-5);
assert_eq!(r.checked_as::<u32>(), None);
let owned = I(12);
assert_eq!(owned.borrow().checked_as::<u32>(), Some(12));

Required methods

Casts the value.

Implementors