Downpass self:不能一次多次借用 `self` 作为可变的

时间:2021-01-09 19:27:08

标签: rust borrow-checker

我想向下传递一个可变对象,以便负责工作和管理应用程序某些方面的实体可以改变世界的某些部分……例如,如果特定项目消失,则使兔子出现。

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();
}

我知道我可以通过...解决这个问题

  • 根本没有穿越世界
  • 让世界在管理器中不可变
  • 将管理器的所有逻辑直接放在世界中

我不是在寻找那些,因为我只是想知道如何拥有一个正常的对象图,在那里我可以忽略需要更改的内容,而不会使一切变得如此繁琐。它应该很简单,但我无法让它工作:

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

我怎样才能把自己贬低给自己的孩子?

0 个答案:

没有答案