I want to downpass a mutable object, so that the entity responsible for working and managing certain aspects of the application can change parts of the world... for example make a bunny appear if a particular item fades away.
pub struct World {
world_items: WorldItemManager
}
impl World {
pub fn new() -> World {
World {
world_items: WorldItemManager{},
}
}
pub fn process(&mut self) {
//
// Uncomment to make it fail:
//
//self.world_items.process(&mut self);
}
}
pub struct WorldItemManager {
// items, events, anything that it should own
}
impl WorldItemManager {
pub fn process(&mut self, _world: &mut World) {
// If the sun stands at the exact spot, it makes something in the _world appear.
// Also: yes, if I don't take a _world argument it compiles. But.. that's the point.
}
}
struct Game {
world: World
}
impl Game {
pub fn new() -> Game {
Game {
world: World::new(),
}
}
pub fn run(&mut self) {
loop {
self.world.process();
}
}
}
fn main() {
let mut game = Game::new();
game.run();
}
I know that I can fix this by..
- not passing the World at all
- making the World not mutable in the manager
- putting all the logic of the manager directly in world
I'm not looking for those, as I just want to find out how I can have a normal object graph where I can downpass what needs changing without making everything so cumbersome. It should be simple, but I can't get it to work:
error[E0499]: cannot borrow `self.world_items` as mutable more than once at a time
--> src/main.rs:16:9
|
16 | self.world_items.process(&mut self);
| ^^^^^^^^^^^^^^^^^-------^---------^
| | | |
| | | first mutable borrow occurs here
| | first borrow later used by call
| second mutable borrow occurs here
How can I downpass myself to a child of myself?
question from:
https://stackoverflow.com/questions/65646749/downpass-self-cannot-borrow-self-as-mutable-more-than-once-at-a-time 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…