简体   繁体   中英

More specific self in function declaration

Given this code:

pub fn handle_events(&mut self) {
    use self::glium::glutin::Event;
    for ev in self.display.poll_events() {
        match ev {
            Event::Closed => self.state = GameState::Exiting,
            Event::KeyboardInput(state, _, Some(key))
                if self.input.keys_pressed.contains_key(&key) =>
                    self.handle_keyboard(state, key),
            _ => (),
        }
    }
}

fn handle_keyboard(&mut self, state: ElementState, key: VirtualKeyCode) {
    ...
}

Rust complains in self.handle_keyboard(state, key) that I cannot borrow a mutable reference of self , since I already made an immutable borrow of self.display in the line for ev in self.display.poll_events() { .

In the case that I want to modify just a field in self which is not in self.display , is it possible to specify that to the compiler? It would be something like this:

fn handle_keyboard(&mut self.field, ...)

No, it's not possible to do that. See if you can rearrange things in some other manner, like taking the specific fields that you need by mutable reference instead of all of self . If it's a private method, the ergonomic regression doesn't matter so much, either.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM