0

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
McKayla
  • 6,879
  • 5
  • 36
  • 48
  • 1
    In short, you need to store the closure in a `Box – Sven Marnach Oct 22 '18 at 09:49
  • 1
    The last error message is indeed not particularly helpful. When applying the `&` operator to create a borrow, you can't specify a lifetime. Rust figures out how long the variable you borrow lives automatically. Since the parser does not expect a lifetime in this location, `'static` is interpreted as a loop label instead. Labels need to be followed by a colon, which is why the parser throws this particular error message. – Sven Marnach Oct 22 '18 at 09:56
  • I'd [suggest an `Option` instead](https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=ec771fbd9a5e15faa242663f8377e81a). – Shepmaster Oct 22 '18 at 17:29

0 Answers0