A generic interface for casting between machine scalars with the
as operator, which admits narrowing and precision loss.
Implementers of this trait AsPrimitive should behave like a primitive
numeric type (e.g. a newtype around another primitive), and the
intended conversion must never fail.
let three: i32 = (3.14159265f32).as_(); assert_eq!(three, 3);
Currently, some uses of the
as operator are not entirely safe.
In particular, it is undefined behavior if:
- A truncated floating point value cannot fit in the target integer type (#10184);
let x: u8 = (1.04E+17).as_(); // UB
- Or a floating point value does not fit in another floating point type (#15536).
let x: f32 = (1e300f64).as_(); // UB
fn as_(self) -> T
Convert a value to another, using the