I have code similar to the following:
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();
}
In reference to the do_later
function that I'm having trouble with and the 3 ways I've tried to fix it...
handle
has an unknown size at compile time. Okay, that's fine, we'll just do it by reference then.
&handle
may not live long enough, blah blah blah lifetimes. Okay, also fine. We just need to specify that it won't ever be cleared from memory by declaring it as static.
&'static handle
spits out this garbage...
error: expected `:`, found `handle`
--> example.rs:13:42
|
13 | self.handle = Some(&'static handle);
| ^^^^^^ expected `:`
I have no idea what's going on. Shouldn't this be valid syntax? If not, what do I need to do differently?