Cannot infer an appropriate lifetime due to conflicting requirements in closure

Hi, I don't really get this Lifetime stuff yet ...

I have this struct:

pub struct Application {
    window: Option<Window>,
    running: bool,
}

which implements this function:

impl Application {
    pub fn run(&self) {
        let event_loop = EventLoop::new();
        let mut window = Window::new("Window", 1280, 720);
        window.init(&event_loop);

        event_loop.run(move |event, _, control_flow| {
        match event {
            _ => *control_flow = if self.running == true { ControlFlow::Poll } else { ControlFlow::Exit },
        }
    });
    }
}

I get this error when accessing the running member of the struct:
cannot infer an appropriate lifetime due to conflicting requirements

anybody know why I can't access it like that and how would I do it instead?

Abstracting a bit, we have:

impl Application {
  pub fn run(&self) {
    event_loop.run(|...| { self.running })
  }
}
  1. This closure depends on self.running, and therefore can not live longer than the Application object we are calling from

  2. However, rust has no idea what event_loop.run does -- that function might store the closure in a way such that the closure tries to outlive the Application.

  3. As for how to fix this -- I'm not particularly sure, I've found Gui + Callbacks + Closures to be troublesome as well. I end up using lots of Rc<...>'s , but I don't know if it's the correct/idiomatic way to resolve this.

1 Like

Hi thanks for you answer.
I experimented a little and according to the winit docs the closure in event_loop.run has a static lifetime.
I also found 2 Solutions

  1. giving the self param of application.run a 'static lifetime specifier solved it but I guess that is the least idiomatic way since application doesn't really have a static lifetime.

  2. Another way to solve it was to move the event_loop.run() call out of the application function an declaring the app variable in the same scope as event_loop. This way I could access it without specifying a lifetime.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.