在Python或C++中,一个类A可以将一些工作委托给另一个类B的实例,并在B中设置A的回调方法。我尝试在Rust中做到这一点,但是到目前为止,我被Rust编译器打败了。
以下是我尝试过的代码,请参见本文末尾的剩余代码。
在A::test中,我尝试使用闭包来获取一个Fn() trait对象作为回调。
以下是我尝试过的代码,请参见本文末尾的剩余代码。
在A::test中,我尝试使用闭包来获取一个Fn() trait对象作为回调。
// let b = B::new(self.finish)); // ideally but would not compile
// let test :Box<Fn(String)> = Box::new(move |msg| {self.finish(msg);}); // cannot infer an appropriate lifetime due to conflicting requirements
// let b = B::new(&test);
// let b = B::new(&Box::new( |msg| {A::finish(&self, msg);} )); // expected trait std::ops::Fn, found closure
// let b = B::new(&Box::new( |msg| {self.finish(msg);} )); // expected trait std::ops::Fn, found closure
目前还没有有效的解决办法。有没有其他方法可以实现这个想法?
非常感谢任何帮助!
或者我基本上是错的吗?Rust是否需要另一种方式来实现这里的想法?
以下是我的测试代码:
struct A {}
impl A {
fn finish(&self, msg: String) {
println!("{}", msg);
}
fn test(&self) {
//let b = B::new(self.finish)); // would not compile
// let test :Box<Fn(String)> = Box::new(move |msg| {self.finish(msg);}); // cannot infer an appropriate lifetime due to conflicting requirements
// let b = B::new(&test);
// let b = B::new(&Box::new( |msg| {A::finish(&self, msg);} )); // expected trait std::ops::Fn, found closure
let b = B::new(&Box::new( |msg| {self.finish(msg);} )); // expected trait std::ops::Fn, found closure
b.start("hi".to_string().clone());
}
}
struct B<'b> {
// cb:fn(msg:String),
cb: &'b Box<Fn(String)>,
}
impl<'b> B<'b> {
fn new(cb: &'b Box<Fn(String)>) -> B<'b> {
B { cb: cb }
}
fn start(&self, msg: String) {
(self.cb)(msg);
}
}
fn main() {
let a = A {};
a.test();
}
rustfmt
或在您的机器上使用cargo fmt
。 - hellow