如何将方法作为回调传递

时间:2019-07-30 11:29:58

标签: callback rust

在Python或C ++中,类A可以将某些工作委派给类Say 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是否要求其他方法在这里实施该想法?

这是我的测试代码

Play Ground Link

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();
}

1 个答案:

答案 0 :(得分:2)

是的,您可以将方法作为回调传递给您的结构,并从该结构的方法中调用它。并且您无需在传递引用时将封闭框装箱:

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();
}

playground

将函数移到新结构时,此框很有用,但情况并非如此。

注意:由于您的函数名为start,我怀疑在您的实际用例中您想启动一个线程,在这种情况下,您可能应该看一下channels而不是回调。

相关问题