我正在尝试围绕两种不同类型制作适配器来完成相同的工作,但我无法重写这两种类型。
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));
}
Run Code Online (Sandbox Code Playgroud)
编译器失败并显示:
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));
}
Run Code Online (Sandbox Code Playgroud)
我能够弄清楚;不需要包装结构。正确的方法是一种普遍特征。我还错过了泛型类型变量的类型范围。
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());
}
Run Code Online (Sandbox Code Playgroud)