假设我有以下代码:
基本上,我正在尝试独立地操作调用者和被调用的方法。但是我遇到了以下编译错误:
trait Saluter {
fn hello(&self);
fn bye(&self);
}
struct A {}
struct B {}
impl Saluter for A {
fn hello(&self) {
println!("Hello A!");
}
fn bye(&self) {
println!("Bye A!");
}
}
impl Saluter for B {
fn hello(&self) {
println!("Hello B!");
}
fn bye(&self) {
println!("Bye B!");
}
}
pub struct Foo {
saluter: Box<dyn Saluter>,
salute: fn (&dyn Saluter),
}
fn main() {
let x = Foo {saluter: Box::new(A{}), salute: Saluter::hello};
let y = Foo {saluter: Box::new(B{}), salute: Saluter::bye};
(x.salute)(x.saluter.borrow()); //Should print "Hello A!"
(y.salute)(y.saluter.borrow()); //Should print "Hello B!"
}
基本上,我正在尝试独立地操作调用者和被调用的方法。但是我遇到了以下编译错误:
let x = Foo {saluter: Box::new(A{}), salute: Saluter::hello};
| ^^^^^^^^^^^^^^ one type is more general than the other
|
= note: expected fn pointer `for<'r> fn(&'r (dyn Saluter + 'r))`
found fn pointer `for<'r> fn(&'r dyn Saluter)`
显然,y也存在同样的错误。我最近才开始学习Rust,所以对于Rust生命周期参数并不熟练,但我觉得它在抱怨这个问题,尽管我无法确定(dyn Salute + 'r)确切的含义。
有没有办法实现我想要的功能,或者在Rust中根本不可能实现?在C++中,我可以轻松地使用指向基类的指针来完成,但我正在努力找到如何在Rust中实现这一点。
T
是无大小限制的(通过在 trait 约束中添加?Sized
),你可以将 trait 对象用作T
,从而实现原始目标,并在不需要动态多态性时获得速度提升。Playground - Aiden4