[][src]Trait az::StaticAs

pub trait StaticAs {
    fn static_as<Dst>(self) -> Option<Dst>
    where
        Self: StaticCast<Dst>
; }

Used to cast values if all possible source type values fit in the destination type.

This trait is different from CheckedAs because with function inlining, the compiler should be able to determine at compile time whether this trait’s method returns Some or None. That is, a particular implementation of this trait should either always return Some or always return None.

This is a convenience trait to enable writing src.static_as::<Dst>(). This would not work with the StaticCast::static_cast method because the StaticCast trait is generic while the static_cast method is not generic.

This trait’s method is suitable for chaining.

Examples

use az::StaticAs;

assert_eq!(15u32.static_as::<i64>(), Some(15));
assert_eq!((-12i32).static_as::<f32>(), Some(-12.0));
// 20_000_003 in f32 is rounded to 20_000_004 (24 bits of precision)
assert_eq!(20_000_003_u32.static_as::<f32>(), Some(20_000_004.0));

The following examples return None even though the value 0 fits in the target type, because in each case there are some possible values of the source type which cannot be converted to the target type.

use az::StaticAs;

// i32 cannot be converted to u64 because of negative numbers
assert!(0i32.static_as::<u64>().is_none());
// f32 cannot be converted to i32 because of NaN, inifinite, and large values
assert!(0f32.static_as::<i32>().is_none());

Required methods

fn static_as<Dst>(self) -> Option<Dst> where
    Self: StaticCast<Dst>, 

Casts the value.

Loading content...

Implementors

impl<T> StaticAs for T[src]

Loading content...