关闭中的Rust可变/不可变借用错误

时间:2017-09-18 11:56:12

标签: rust ownership

我正在尝试抽象glium箱子的初始化,但我有所有权问题。我一直在查看文档,看起来它可能与此规则有关:

  
      
  1. 在任何时候,你可以有以下两种:      
        
    • 一个可变的参考文献。
    •   
    • 任意数量的不可变引用。
    •   
  2.   

我认为我理解规则,它如何应用以及它存在的原因,但我无法看到我的代码发生了什么。我创建了一个清理过的例子:

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();
    });
}

我收到此错误:

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

如果renderer不可变,我会得到这个:

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 个答案:

没有答案