我有两个完全相似的 struct A和B.我正在try 将A和B都转换为另一种类型C.A、B和C的定义如下所示.
pub struct A {
pub a: i32,
}
pub struct B {
pub a: i32,
}
pub struct C {
pub b: i32,
}
我将A转换为C的实现如下所示:
impl From<A> for C {
fn from(a: A) -> C {
C {b: a.a}
}
}
因为A和B都很相似,为了从B转换为C,目前我有一个副本
实施上述定义的From
项.
我正在寻找一种方法,使From
实现泛型,并仅限于使用
A和B.我在这里的实施情况如下:
trait Types {}
impl Types for A {}
impl Types for B {}
impl<T: Types> From<T> for C where T: Types {
fn from(entity: T) -> C {
C { b: entity.a }
}
}
但当我用上面的代码编译程序时,我得到以下错误,
error[E0609]: no field `a` on type `T`
|
27 | impl<T: Types> From<T> for C where T: Types {
| - type parameter 'T' declared here
我想知道解决这个错误的方法,因为我别无 Select ,只能保留A和B并避免代码重复.