[][src]Function az::static_cast

pub fn static_cast<Src: StaticCast<Dst>, Dst>(src: Src) -> Option<Dst>

Casts the value, returning None if the destination type cannot hold all values of the source type.

This function is different from checked_cast because with function inlining, the compiler should be able to determine at compile time whether this function returns Some or None.

Examples

assert_eq!(az::static_cast::<u32, i64>(15), Some(15));
assert_eq!(az::static_cast::<i32, f32>(-12), Some(-12.0));
// 20_000_003 in f32 is rounded to 20_000_004 (24 bits of precision)
assert_eq!(az::static_cast::<u32, f32>(20_000_003), 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.

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