[−][src]Trait az::StaticCast
Used to cast values if all possible source type values fit in the destination type.
This trait is different from CheckedCast
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
.
It is normally easier to use the StaticAs
trait instead of this trait.
Examples
use az::StaticCast; let a: Option<i64> = 15u32.static_cast(); assert_eq!(a, Some(15)); assert_eq!(StaticCast::<f32>::static_cast(-12i32), Some(-12.0)); // 20_000_003 in f32 is rounded to 20_000_004 (24 bits of precision) assert_eq!(StaticCast::<f32>::static_cast(20_000_003_u32), 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::StaticCast; // i32 cannot be converted to u64 because of negative numbers assert!(StaticCast::<u64>::static_cast(0i32).is_none()); // f32 cannot be converted to i32 because of NaN, inifinite, and large values assert!(StaticCast::<i32>::static_cast(0f32).is_none());
Required methods
fn static_cast(self) -> Option<Dst>
Casts if the conversion works for all source type values,
otherwise returns None
.