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

后端 未结 2 711
南方客
南方客 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:59

    Here is an example of the fixed code:

    use std::cell::Cell;
    
    fn main() {
        let should_end = Cell::new(false);
        let mut input = Input::new();
        input.add_handler(Box::new(|a| {
            match a {
                1 => {
                    should_end.set(true);
                }
                _ => {
                    println!("{} {}", a, should_end.get())
                }
            }
        }));
        let mut fail_safe = 0;
        while !should_end.get() {
            if fail_safe > 20 {break;}
            input.handle();
            fail_safe += 1;
        }
    }
    
    pub struct Input<'a> {
        handlers: Vec>,
    }
    
    impl<'a> Input<'a> {
        pub fn new() -> Self {
            Input {handlers: Vec::new()}
        }
        pub fn handle(&mut self) {
            for a in vec![21,0,3,12,1,2] {// it will print the 2, but it won't loop again
                for handler in &mut self.handlers {
                    handler(a);
                }
            }
        }
        pub fn add_handler(&mut self, handler: Box) {
            self.handlers.push(handler);
        }
    }
    

提交回复
热议问题