我正试图围绕两种不同的类型制作适配器,它们做着相同的工作,但我无法重写这两种类型。
X
有一个使用self
的方法,因此运行时多态包装器不适用。唯一的选择是静态通用方法。
struct X {}
impl X {
fn f(self, n: i32) {
println!("n = {}", n);
}
fn new() -> X {
X {}
}
}
struct AdapterX {
x: X
}
impl AdapterX {
fn uf(self, n: i32) {
self.x.f(n)
}
fn new(x: X) -> AdapterX {
AdapterX { x: x }
}
}
fn useAdapted<T>(a: T) {
a.uf(10)
}
fn main() {
let x = X::new();
useAdapted::<AdapterX>(AdapterX::new(x));
}
编译器失败,出现:
error: no method named `uf` found for type `T` in the current scope
a.uf(10)
^~
问题就在这里:
fn useAdapted<T>(a: T) {
a.uf(10)
}
上面写着
给我任何可能的类型,我将在其上调用
uf
方法
这显然是无稽之谈,因为你可以输入String
、bool
、HashMap
、File
或。。。。(你明白了(。
没有方法uf
适用于每个类型,因此编译器告诉您是这样。正如您所发现的,您必须在具有一个或多个特征的泛型类型上提供绑定。方法和来自这些特征的相关函数将在方法内部可用。
还要注意,Rust样式是snake_case
;该函数应被称为CCD_ 10。
我能够弄清楚;不需要包装结构。正确的方式是一种共性。我还错过了泛型类型变量的类型作用域。
struct X {}
impl X {
fn f(self, n: i32) {
println!("n = {}", n);
}
fn new() -> X {
X {}
}
}
trait Adapter<T> {
fn uf(self, n: i32);
}
impl Adapter<X> for X {
fn uf(self, n: i32) {
self.f(n)
}
}
struct Y {}
impl Y {
fn g(self, n: f32) {
println!("m = {}", n);
}
fn new() -> Y {
Y {}
}
}
impl Adapter<Y> for Y {
fn uf(self, n: i32) {
self.g(n as f32)
}
}
fn use_adapted<A, T: Adapter<A>>(a: T) {
a.uf(10)
}
fn main() {
use_adapted(X::new());
use_adapted(Y::new());
}