callback - 如何将方法作为回调传递
问题描述
在 Python 或 C++ 中,类说 A 可以将一些工作委托给类说 B 的另一个实例,并在 B 中设置 A 的回调方法。我尝试在 Rust 中这样做,但到目前为止我一无所获,被 Rust 编译器击败.
这是我尝试过的代码,其余代码在本文末尾。
在 A::test 中,我尝试使用闭包来获取 Fn() 特征对象作为回调。
// 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();
}
解决方案
是的,您可以将方法作为回调传递给您的结构,并从该结构的方法中调用它。当您传递参考时,您不需要将闭包装箱:
struct A {}
impl A {
fn finish(&self, msg: String) {
println!("{}", msg);
}
fn test(&self) {
let fun = |msg: String| self.finish(msg);
let b = B::new(&fun);
b.start("hi".to_string().clone());
}
}
struct B<'b> {
cb: &'b Fn(String),
}
impl<'b> B<'b> {
fn new(cb: &'b Fn(String)) -> B<'b> {
B { cb }
}
fn start(&self, msg: String) {
(self.cb)(msg);
}
}
fn main() {
let a = A {};
a.test();
}
当您将函数移动到新结构时,该框很有用,这不是您的情况。
注意:当您的函数被调用start
时,我怀疑在您的实际用例中您想要启动一个线程,在这种情况下,您可能应该查看通道而不是回调。
推荐阅读
- c++ - 是否可以在具有基类定义的映射中传递子类对象?
- python - 如何从连续行中查找损益百分比
- django - 如何在 Django Rest Framework 中使用 LimitOffSetPagination 而不是 PageNumberPagination?
- javascript - 为什么我的引导折叠功能在页面刷新后不起作用?
- javascript - 无法在 Polymer 中进行用户定义的函数调用
- powerbi - 如何计算 PowerBI 中每个类别的比率?
- android - 是否可以使用 Model 类在 JSONArray 中序列化 JSONArray?
- javascript - 将输入转换为字符串/变量并在警报中使用
- spring-boot - 如何将日期作为参数从控制器传递到 API?
- python - Web Scraping 性能问题 EC2 与家用 PC