pub trait ConvExact<S>: Sized {
type Error: Into<RangeError> + Into<Error> + Error;
// Required method
fn try_conv_exact(s: S) -> Result<Self, Self::Error>;
// Provided method
fn conv_exact(s: S) -> Self { ... }
}Expand description
Generic “from” conversion trait for exact conversions
This trait is provided as an implementation aid only, hence there is no
CastExact (in most cases you can just use Cast).
§Implementing exact conversions
Implement conversions which cannot lose precision using this trait.
Implementations of ConvTo<S, R> are implied for all
R: Rounding modes provided by this crate (see
§ Implied implementations).
§Example
use easy_cast::ConvExact;
use std::convert::Infallible;
struct MyBigInt { /* details */ }
// Support conversion from i32:
impl ConvExact<i32> for MyBigInt {
type Error = Infallible;
fn try_conv_exact(i: i32) -> Result<Self, Infallible> {
Ok(todo!())
}
// optionally also impl fn conv_exact
}Note that in practice you’ll probably want to support conversion from many
integer types using macro_rules!. Or you could “cheat” with a generic
impl<S: Into<i128>> ConvExact<S> for MyBigInt { ... }.
Required Associated Types§
Sourcetype Error: Into<RangeError> + Into<Error> + Error
type Error: Into<RangeError> + Into<Error> + Error
Conversion error type
This should be either Infallible or RangeError.
Required Methods§
Sourcefn try_conv_exact(s: S) -> Result<Self, Self::Error>
fn try_conv_exact(s: S) -> Result<Self, Self::Error>
Try converting from S to Self
Provided Methods§
Sourcefn conv_exact(s: S) -> Self
fn conv_exact(s: S) -> Self
Convert from S to Self
Use this method only when success is expected. On error, this method may panic or may exhibit § Fallback behaviour.
§Implementing
Implementing this method directly (with fallback behaviour) is optional. In debug builds, this method must panic on error.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".