I would like to cast a u64 value to a generic numeric type, something like
fn f<T: AppropriateTrait>(v: u64) -> T {
v as T
}
and have it behave semantically like, e.g., 259u64 as u8
, i.e., it should just take the least significant bits. Unfortunately, the FromPrimitive::from_u64
function returns an Option<T>
, with None
if the input value doesn't fit.
This here works:
fn f<T: FromPrimitive + Int + ToPrimitive>(v: u64) -> T {
T::from_u64(v & T::max_value().to_u64().unwrap()).unwrap()
}
But it's very verbose and inelegant. Is there a better way?
Edit: I'm only interested in casting to integer types like u8, u16, etc., no funky stuff.