Hello, I am new to Rust. I'm writing a program where one object (One) owns another (Two). One regularly calls into Two but occasionally I need Two to notify One that some particular event has occurred internally to Two.
Can someone suggest a design pattern/method to make this a possibility?
struct One {
count: u32,
two: Two,
}
impl One {
fn new() -> One {
One {
count: 0,
two: Two::new(),
}
}
fn go(&mut self, n: u32) {
while self.count != n {
self.two.step(self);
}
}
fn step(&mut self) {
self.count += 1;
}
}
struct Two {
count: u32,
}
impl Two {
fn new() -> Two {
Two {
count: 0,
}
}
fn step(&mut self, one: &mut One) {
self.count += 1;
if (self.count % 10) == 0 {
one.step();
}
}
}
fn main() {
let mut one = One::new();
one.go(20);
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0499]: cannot borrow `self.two` as mutable more than once at a time
--> src/main.rs:17:13
|
17 | self.two.step(self);
| ^^^^^^^^^----^----^
| | | |
| | | first mutable borrow occurs here
| | first borrow later used by call
| second mutable borrow occurs here
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:17:27
|
17 | self.two.step(self);
| -------- ---- ^^^^ 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 `playground` (bin "playground") due to 2 previous errors
My actual system is this: I have a Device with multiple Components. The components (and Device, actually) implement a Writable trait. So the Device calls component.write() often, and the interface across all devices is the same. Some components need to let the Device know that an event has occurred. For example, component1 needs to tell the device that it should not use component2 in the next time step. How?