我有一个struct只有一个字段的泛型,只能是i32or 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
现在我想添加一个返回字段 value 的方法as f32,无论它是i32还是f32。我知道这种转换应该总是可能的,因为字段类型仅限于上面提到的两种,但我该怎么做呢?显然as只适用于原始类型,我尝试走这From条路,但我做错了什么,这不起作用。
fn to_f32(&self) -> f32 where T: From<i32> {
        f32::from(self.field);
}
Run Code Online (Sandbox Code Playgroud)
    你是对的,as只适用于具体类型。
使用FromorInto特征进行转换是一个很好的方法,但这些方法并未针对 i32 -> f32 转换实现。正如 Matthieu M. 所说,原因很可能是潜在的有损转换。
您必须使用f64而不是f32.
我建议将特征更改为:
trait MyInt: Copy + Into<f64> {
    fn blank();
}
Run Code Online (Sandbox Code Playgroud)
然后您可以添加方法来进行转换:
fn to_f64(&self) -> f64 {
    self.field.into()
}
Run Code Online (Sandbox Code Playgroud)