pub trait TryCast<T> {
type Error;
// Required method
fn try_cast(self) -> Result<T, Self::Error>;
}Expand description
Fallible conversion between fastnum numeric types (akin to TryFrom, but
for fastnum).
TryCast returns Result<T, Error>, where Error describes why the
conversion failed (e.g., out-of-range for the target type or invalid sign
conversion).
Use TryCast when:
- the value may not fit into the target type (overflow/underflow);
- information could be lost (e.g., negative to unsigned);
- you need explicit error handling rather than silent truncation.
§Examples:
use fastnum::*;
// Successful conversion (value fits in the target type)
let x = u256!(42);
let y: U128 = x.try_cast().unwrap();
assert_eq!(u128!(42), y);
// Failing conversion (negative to unsigned)
let neg = i256!(-1);
assert!(<I256 as TryCast<U64>>::try_cast(neg).is_err());Tips:
- If the conversion is always valid by design — prefer
Cast. - If range/sign must be checked — prefer
TryCast.
Required Associated Types§
Required Methods§
Sourcefn try_cast(self) -> Result<T, Self::Error>
fn try_cast(self) -> Result<T, Self::Error>
Attempts to convert self into T, returning an error on failure.
Use this method when the conversion may be lossy or out-of-range.
§Examples:
use fastnum::*;
// In-range: succeeds
let a = u256!(18446744073709551615);
let b: U64 = a.try_cast().unwrap();
assert_eq!(u64!(18446744073709551615), b);
// Out-of-range: fails with an error
let big = u256!(18446744073709551616);
let _ = <U256 as TryCast<U64>>::try_cast(big).unwrap_err();