pub trait CastFrom<T>: Sized {
// Required method
fn cast_from(value: T) -> Self;
}
Expand description
Like From
but also support safe casts from/to usize
and isize
.
From | TryFrom | as cast | CastFrom | |
---|---|---|---|---|
No runtime check | ✅ | ❌ | ✅ | ✅ |
usize <-> u64 1 | ❌ | ✅ | ✅ | ✅ |
No truncation | ✅ | ✅ | ❌ | ✅ |
No change of sign | ✅ | ✅ | ❌ | ✅ |
From<usize>
is not implemented for u64
even on platforms
where the pointer width is 64 bit or lower (all currently supported
targets).
Thus the following code fails to compile:
let a = usize::MAX;
let b = u64::from(a);
// Error: the trait `From<usize>` is not implemented for `u64`
Instead you have to resort to using TryFrom
and
unwrap
:
let a = usize::MAX;
let b = u64::try_from(a).unwrap();
or using a potentially truncating/signedness-changing numeric cast using
as
:
let a = usize::MAX;
let b = a as u64;
If you want to guarantee that there are no runtime panics and the value will
not be truncated, you can instead use CastFrom
or CastInto
:
use platform_cast::{CastFrom, CastInto};
let a = usize::MAX;
let b = u64::cast_from(a);
// Alternatively:
let b: u64 = a.cast_into();
The casts available depends on the target platform. The following code will only compile if the target pointer width is 64 bit or more.
use platform_cast::CastFrom;
let a = u64::MAX;
let b = usize::cast_from(a);
// On 32-bit targets: error[E0277]: the trait bound `usize: CastFrom<u64>`
is not satisfied
Assuming a target with a pointer width of 64. ↩
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.