Hi all, I'm writing a small game to help myself learn rust. I'm trying to do some basic event handling, but am being shot down by compiler for the following code:
trait PlatformHandler {
fn on_mouse_down(&mut self);
}
struct Platform {}
impl Platform {
fn pump_events(&mut self, handler: &mut dyn PlatformHandler) {
// some code detected a mouse press, notify the handler
handler.on_mouse_down();
}
}
struct Engine {
click_count: i32,
platform: Platform,
}
impl Engine {
fn new() -> Engine {
Engine {
click_count: 0,
platform: Platform {},
}
}
fn advance(&mut self) {
// attempt to pass in visitor-esque reference to self each advance so that
// we don't have a listener registration/unregistration observer system
// as there will only be one listener
self.platform.pump_events(self); // *** FAIL ***
}
}
impl PlatformHandler for Engine {
fn on_mouse_down(&mut self) {
println!("mouse down!");
self.click_count += 1;
}
}
fn main() {
let mut engine = Engine::new();
loop {
engine.advance();
}
}
When I build this, I get the following error:
Compiling foo v0.1.0 (/mnt/data/projects/foo)
error[E0499]: cannot borrow `self.platform` as mutable more than once at a time
--> src/main.rs:30:9
|
30 | self.platform.pump_events(self); // *** FAIL ***
| ^^^^^^^^^^^^^^^^^^^^^^^^^^----^
| | |
| | first mutable borrow occurs here
| second mutable borrow occurs here
| first borrow later captured here by trait object
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:30:35
|
30 | self.platform.pump_events(self); // *** FAIL ***
| ------------- ----------- ^^^^ second mutable borrow occurs here
| | |
| | first borrow later used by call
| first mutable borrow occurs here
For more information about this error, try `rustc --explain E0499`.
error: could not compile `foo` due to 2 previous errors
So the first mutable borrow to self.platform
makes sense, great. I am then just passing along the already mutable reference to self
into pump_events
, which should be fine. I don't see where the second borrow happens, even with the error message underlining the code.
My belief is that now I have two borrows:
- One mutable borrow to
self
- One mutable borrow to
platform
What am I missing here, and how can I get this to work? Thanks for your time.