I have a generic struct
with one field, that can only be i32
or f32
.
trait MyInt {
fn blank();
}
impl MyInt for i32 {
fn blank() {
unimplemented!()
}
}
impl MyInt for f32 {
fn blank() {
unimplemented!()
}
}
struct MyStruct<T> where T: MyInt {
field: T
}
impl<T> MyStruct<T> where T: MyInt {
fn new(var: T) -> MyStruct<T> {
MyStruct {
field: var
}
}
}
Now I want to add a method which returns field value as f32
, whether it's i32
or f32
. I know that this cast should always be possible since field types are limited to two mentioned above, but how do I go about it? Apparently as
only works on primitive types and I tried going the From
route, but I am doing something wrong, this doesn't work.
fn to_f32(&self) -> f32 where T: From<i32> {
f32::from(self.field);
}