传递闭包作为参数,并保存以供以后使用

时间:2018-10-22 00:00:51

标签: rust object-lifetime

我的代码类似于以下内容:

pub struct Delay {
    // This line would also need to change, obviously
    handle: Option<&'static Fn()>,
}

impl Delay {
    pub fn new() -> Delay {
        Delay { handle: None }
    }

    pub fn do_later<H>(&mut self, handle: H)
    where
        H: Fn(),
    {
        // This line is the problem child. Of all the things I've tried
        // none of them work. Including...
        self.handle = Some(handle);
        self.handle = Some(&handle);
        self.handle = Some(&'static handle);
    }

    pub fn do_now(&self) {
        match self.handle {
            Some(handle) => handle(),
            None => (),
        };
    }
}

pub struct Action;

impl Action {
    pub fn new() -> Action {
        Action
    }

    pub fn link(&self, target: &mut Delay) {
        target.do_later(|| {
            println!("Doin' stuff!!");
        })
    }
}

fn main() {
    let mut delay = Delay::new();
    let action = Action::new();

    action.link(&mut delay);
    delay.do_now();
}

参考我遇到的do_later函数以及尝试修复它的3种方法...

handle在编译时大小未知。好的,那很好,那我们就参考一下。

&handle可能寿命不长,等等。好的,还可以。我们只需要声明它为静态就可以指定永远不会从内存中清除它。

&'static handle吐出这个垃圾...

error: expected `:`, found `handle`
  --> example.rs:13:42
   |
13 |             self.handle = Some(&'static handle);
   |                                         ^^^^^^ expected `:`

我不知道发生了什么。这不是有效的语法吗?如果没有,我该怎么做?

0 个答案:

没有答案