pub trait PrimitiveFrom<T> {
// Required method
fn from(_: T) -> Self;
}
Expand description
A generic interface for casting between machine scalars with the
as
operator, which admits narrowing and precision loss.
Implementers of this trait PrimitiveFrom should behave like a primitive
numeric type (e.g. a newtype around another primitive), and the
intended conversion must never fail.
§Examples
let three: i32 = PrimitiveFrom::from(3.14159265f32);
assert_eq!(three, 3);
§Safety
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 = PrimitiveFrom::from(1.04E+17); // UB
- Or a floating point value does not fit in another floating point type (#15536).
ⓘ
let x: f32 = PrimitiveFrom::from(1e300f64); // UB
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.