“error: closure may outlive the current function” but it will not outlive it

后端 未结 2 709
南方客
南方客 2021-01-04 10:07

When I try to compile the following code:

fn main() {

    (...)

    let mut should_end = false;

    let mut input = Input::new(ctx);

    input.add_handle         


        
2条回答
  •  长情又很酷
    2021-01-04 10:52

    The problem is not your closure, but the add_handler method. Fully expanded it would look like this:

    fn add_handler<'a>(&'a mut self, handler: Box)
    

    As you can see, there's an implicit 'static bound on the trait object. Obviously we don't want that, so we introduce a second lifetime 'b:

    fn add_handler<'a, 'b: 'a>(&'a mut self, handler: Box)
    

    Since you are adding the handler object to the Input::handlers field, that field cannot outlive the scope of the handler object. Thus we also need to limit its lifetime:

    pub struct Input<'a> {
        handlers: Vec>,
    }
    

    This again requires the impl to have a lifetime, which we can use in the add_handler method.

    impl<'a> Input<'a> {
        ...
        pub fn add_handler(&mut self, handler: Box) {
            self.handlers.push(handler);
        }
    }
    

    Now all that's left is using a Cell to control access to your should_end flag.

提交回复
热议问题