我有一个小游戏应用程序,使用特征对象来处理关键事件并修改应用程序状态:
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)
}
}
这无法编译,因为最后一个handle_key_events
函数:
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
我只想使用GameScene
对象来修改的成员TypingApp
,我该如何修复这个编译错误?谢谢!