Rust mutable/inmutable borrow error in closure

82 views Asked by At

I'm trying to abstract the initialisation of the glium crate but I'm having ownership problems. I've been looking the documentation and looks like it may be related to this rule:

  1. At any given time, you can have either but not both of:
    • One mutable reference.
    • Any number of immutable references.

I think that I understand the rule, how it applies and why it exists, but I can't see what's happening with my code. I've created a cleaned-up example:

extern crate glium;

use glium::glutin;

pub struct Renderer {
    pub events_loop: glium::glutin::EventsLoop,
    pub display: glium::Display,
}

impl Renderer {
    pub fn new() -> Renderer {
        let events_loop = glutin::EventsLoop::new();
        let window = glutin::WindowBuilder::new();
        let context = glutin::ContextBuilder::new();
        let display = glium::Display::new(window, context, &events_loop).unwrap();

        Renderer {
            events_loop: events_loop,
            display: display,
        }
    }
}

fn main() {
    let mut renderer = Renderer::new();

    renderer.events_loop.poll_events(|event| {
        // Some event handling logic with `match`, somewhere I've this line:
        let window_size = renderer.display.gl_window().get_inner_size_pixels().unwrap();
    });
}

I get this error:

error[E0502]: cannot borrow `renderer` as immutable because `renderer.events_loop` is also borrowed as mutable
  --> src/main.rs:27:38
   |
27 |     renderer.events_loop.poll_events(|event| {
   |     --------------------             ^^^^^^^ immutable borrow occurs here
   |     |
   |     mutable borrow occurs here
28 |         // Some event handling logic with `match`, somewhere I've this line:
29 |         let window_size = renderer.display.gl_window().get_inner_size_pixels().unwrap();
   |                           -------- borrow occurs due to use of `renderer` in closure
30 |     });
   |      - mutable borrow ends here

If renderer is not mutable, I get this one:

error[E0596]: cannot borrow immutable field `renderer.events_loop` as mutable
  --> src/main.rs:27:5
   |
25 |     let renderer = Renderer::new();
   |         -------- consider changing this to `mut renderer`
26 |
27 |     renderer.events_loop.poll_events(|event| {
   |     ^^^^^^^^^^^^^^^^^^^^ cannot mutably borrow immutable field
0

There are 0 answers