pub trait ConvApprox<T>: Sized {
    fn try_conv_approx(x: T) -> Result<Self>;

    fn conv_approx(x: T) -> Self { ... }
}
Expand description

Like From, but for approximate numerical conversions

On success, the result must be approximately the same as the input value: the difference must be smaller than the precision of the target type. For example, one may have i32::conv_approx(1.9f32) = 1 or f32::conv_approx(1f64 + (f32::EPSILON as f64) / 2.0) = 1.0.

Precise rounding mode should usually be truncation (round towards zero), but this is not required. Use ConvFloat where a specific rounding mode is required.

The sister-trait CastApprox supports “into” style usage.

Required Methods§

Try converting from T to Self, allowing approximation of value

This conversion may truncate excess precision not supported by the target type, so long as the value is approximately equal, from the point of view of precision of the target type.

This method should allow approximate conversion, but fail on input not (approximately) in the target’s range.

Provided Methods§

Converting from T to Self, allowing approximation of value

This method must return the same result as Self::try_conv_approx where that method succeeds, but differs in the handling of errors:

  • In debug builds the method panics on error
  • Otherwise, the method may panic or may return a different value, but like with the as keyword all results must be well-defined and safe.

Default implementations use Self::try_conv_approx and panic on error. Implementations provided by this library will panic in debug builds or if the always_assert feature flag is used, and otherwise will behave identically to the as keyword.

This mirrors the behaviour of Rust’s overflow checks on integer arithmetic in that it is a tool for diagnosing logic errors where success is expected.

Examples found in repository?
src/traits.rs (line 195)
194
195
196
    fn cast_approx(self) -> T {
        T::conv_approx(self)
    }

Implementations on Foreign Types§

Implementors§