pub trait CastTo<T, R: Rounding>: Sized {
type Error: Into<R::MaximumError> + Error;
// Required methods
fn try_cast_to(self, mode: R) -> Result<T, Self::Error>;
fn cast_to(self, mode: R) -> T;
}Expand description
Generic “into” conversion trait with specified rounding mode
This trait supports Into- and TryInto-like conversions, but with a
specified rounding mode:
- Conversions may be fallible, like
TryInto. - Conversions may be lossy, according to the
Roundingmode used. - Conversions must be value-preserving, like
Into. For example,-1_i8and-1_i32are conceptually the same value while255_u8is conceptually a different value.
The Rounding mode must be specified:
let x: i32 = 3.14192.cast_to(Floor);
assert_eq!(x, 3);
let y = (1i32 << 30) - 1;
let z: f32 = y.cast_to(Nearest); // this example rounds up
assert_eq!(z as i32, 1i32 << 30);Usage with Exact and Approx is equivalent to usage of Cast and
CastApprox respectively.
This trait is automatically implemented for every implementation of ConvTo.
Required Associated Types§
Sourcetype Error: Into<R::MaximumError> + Error
type Error: Into<R::MaximumError> + Error
Conversion error type
This should be one of Infallible, RangeError or Error.
Required Methods§
Sourcefn try_cast_to(self, mode: R) -> Result<T, Self::Error>
fn try_cast_to(self, mode: R) -> Result<T, Self::Error>
Try converting from Self to T, rounding according to mode
Sourcefn cast_to(self, mode: R) -> T
fn cast_to(self, mode: R) -> T
Convert from Self to T, rounding according to mode
Use this method only when success is expected. On error, this method may panic or may exhibit § Fallback behaviour.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".