0

I am attempting to encapsulate the event loop execution of glutin/winit in a custom class described in the example section over here: https://docs.rs/glutin/0.26.0/glutin/window/struct.Window.html

Now I am running into the issue of handling the ownership of self members when attempting to access them in a closure passed to a method:

pub struct GameWindow {
    context: ContextWrapper<PossiblyCurrent, Window>,
    event_loop: EventLoop<()>,
    gl: Rc<gl::Gl>,
}

impl GameWindow {
    pub fn run(&self) {
        self.event_loop.run(move |event, _, control_flow| {
            *control_flow = ControlFlow::Poll;

            match event {
                Event::WindowEvent {
                    event: WindowEvent::CloseRequested,
                    ..
                } => {
                    *control_flow = ControlFlow::Exit;
                }
                Event::MainEventsCleared => {
                    unsafe {
                        self.gl.Clear(gl::COLOR_BUFFER_BIT);
                    }
                    self.context.swap_buffers().unwrap();
                }
                _ => (),
            }
        });
    }
}

The compiler complains with the following error: self has an anonymous lifetime '_ but it needs to satisfy a 'static lifetime requirement.

Applying that suggestion (even though I am not familiar with the static lifetime yet) yields an error about accessing self.event_loop: Cannot move out of self.event_loop which is behind a shared reference.

What is a proper way to resolve this issue?

Christian Ivicevic
  • 10,071
  • 7
  • 39
  • 74
  • I believe you are trying to circumvent an actual unsafe pattern, which will lead to various kinds of errors, but maybe this could send you in the right direction. [How do I use static lifetimes with threads?](https://stackoverflow.com/questions/30562443/how-do-i-use-static-lifetimes-with-threads) – Félix Adriyel Gagnon-Grenier May 01 '21 at 18:38
  • I believe the logical problem here, is that there is no guarantee that self will still exist when the closure will actually execute. – Félix Adriyel Gagnon-Grenier May 01 '21 at 18:39
  • `EventLoop::run` consumes `self`. You must have ownership of the `EventLoop` (and hence the `GameWindow` that contains it) to call it. – AlphaModder May 02 '21 at 00:29

1 Answers1

0

I solved this particular issue by making event_loop of type Option<EventLoop<()>> and the run method invoking self.event_loop.take().unwrap().run(...). Unfortunately I really dislike the semantics of this solution since in theory the event loop exists during the entire lifespan of the window and my solution leaving a None in its place doesn't feel right at all.

Christian Ivicevic
  • 10,071
  • 7
  • 39
  • 74