I have a small game app using trait object to handle key events and modify app state:
pub trait GameScene {
fn handle_key_events(&self, app: &mut TypingApp, key_event: KeyEvent) -> Result<()>;
}
pub struct StartupScene {}
impl GameScene for StartupScene {
fn handle_key_events(&self, app: &mut TypingApp, key_event: KeyEvent) -> Result<()> {
todo!()
}
}
pub struct TypingApp {
/// lots of other members here
/// ......
/// modify above members according to the user's input
pub cur_scene: Box<dyn GameScene>
}
impl Default for TypingApp {
fn default() -> Self {
Self {
cur_scene: Box::new(StartupScene{})
}
}
}
impl TypingApp {
pub fn handle_key_events(&mut self, key_event: KeyEvent) -> Result<()> {
self.cur_scene.handle_key_events(self, key_event)
}
}
This cannot be compiled because the last handle_key_events
function:
error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
--> src/app.rs:53:9
|
53 | self.cur_scene.handle_key_events(self, key_event)
| --------------^-----------------^^^^^^^^^^^^^^^^^
| | |
| | immutable borrow later used by call
| mutable borrow occurs here
| immutable borrow occurs here
I just want to use GameScene
object to modify members of TypingApp
, how can I fix this compile error? Thanks!