I am trying to understand generic functions. I know this topic has been discussed extensively, but I can't seem to wrap my head around some details.
I am attempting something similar to this, but even simpler. I just want a double function that multiplies the argument by two and I want it to work for any float or integer type. So far I have this:
use std::convert::From;
use std::ops::Mul;
fn double<A>(x: A) -> A
where A: Mul<Output = A> + From<f32> {
return x * A::from(2f32);
}
This works fine, when I call it with a float (f32 or f64):
println!("{:?}", double(2f64));
This gives me 4.0.
But it fails for any integer type, for example:
printl!("{:?}", double(2i32));
This gives the following error:
println!("{:?}", double(2i32));
------ ^^^^ the trait `From<f32>` is not implemented for `i32`
I understand the error. There is no general way to cast a float to an integer. It's ambiguous how that is supposed to work, if I wanted to cast 2.5 inside my function instead of 2.0.
I know there is the TryFrom trait, but I cannot figure out, how to make use of it in this situation.
I tried it the other way around, i.e. requiring A to implement From<u32> for example, but this just switches the error from occurring with integers to occur with floats. But what surprised me is that it also leads to an error when I call the function with a signed integer like 2i32.
What am I missing? How can I realize a generic double function over any number type?