I have been working on a function which I would like to make generic over all integer types. I have therefore used the Integer
trait from the num
crate https://docs.rs/num/latest/num/trait.Integer.html however, my function requires my to be able to type cast both to and from my input type e.g.
fn main() {
test(54_u8);
}
fn test<T> (x: T)
where T: num::Integer + std::fmt::Display {
assert_eq!(10_u64, x as u64);
assert_eq!(54_i32 as T, x);
}
Where the code fails with the error message
an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
How can I typecast a generic integer? Thanks,
num::FromPrimitive
and num::ToPrimitive
can help to switch back and forth between num::Integer
and a concrete type.
fn main() {
test(10_u8);
test(54_u8);
}
fn test<T>(x: T)
where
T: num::Integer + num::FromPrimitive + num::ToPrimitive + Copy,
{
if T::from_u64(10) == Some(x) {
println!("this is ten");
}
if let Some(54) = x.to_i32() {
println!("this is fifty-four");
}
}