Skip to main content

CastTo

Trait CastTo 

Source
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 Rounding mode used.
  • Conversions must be value-preserving, like Into. For example, -1_i8 and -1_i32 are conceptually the same value while 255_u8 is 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§

Source

type Error: Into<R::MaximumError> + Error

Conversion error type

This should be one of Infallible, RangeError or Error.

Required Methods§

Source

fn try_cast_to(self, mode: R) -> Result<T, Self::Error>

Try converting from Self to T, rounding according to mode

Source

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".

Implementors§

Source§

impl<R: Rounding, S, T: ConvTo<S, R>> CastTo<T, R> for S

Source§

type Error = <T as ConvTo<S, R>>::Error