首页 文章

如何获取非功能代码块的变量所有权

提问于
浏览
2
for tower in &mut game.towers {
    tower.towers_attack(&mut game)
};

cannot borrow game as mutable more than once at a time [E0499]

我的代码正在运行,但我正在重构它以使其更有意义 .

工作是什么(主要要点是在游戏对象上可变地循环两次是好的,但这是因为函数拥有'游戏'的所有权?)

impl Attack for Game {
    fn towers_attack(&mut self) {
        for tower in &mut self.towers {
            tower.attacked = false;
            if tower.hp.is_positive() {
                for creep in &mut self.lane_creeps {
                    if tower.position.distance_between(creep.position) < 12.0 &&
                       creep.side != tower.side && !tower.attacked {
                        creep.hp -= tower.attack_damage as i32;
                        tower.attacked = true;
                        break;
                    }
                }
            }
        }
    }
}

game.towers_attack();

将第一个循环移到函数外部并在 tower 而不是 game.tower 上实现会导致问题 .

我很困惑自己,我相信我只需要将 game 的所有权归还 for tower in &mut game.towers { tower.towers_attack(&mut game) }; 然后在退出时归还所有权,因此如果我明确授予所有权,则不会发生借款,但我不确定这是否可行或有意义 .

towers_attack 函数是

impl TowerAttack for Tower {
    fn towers_attack(&mut self, game: &mut Game) {
        self.attacked = false;
        if self.hp.is_positive() {
            for creep in &mut game.lane_creeps {
                if self.position.distance_between(creep.position) < 12.0 &&
                   creep.side != self.side && !self.attacked {
                    creep.hp -= self.attack_damage as i32;
                    self.attacked = true;
                    break;
                }
            }
        }
    }
}

1 回答

  • 4
    for tower in &mut game.towers {
        tower.towers_attack(&mut game)
    }
    

    Rust会阻止此调用,因为 towers_attack 的实现可能是:

    fn towers_attack(game: &mut Game) {
        game.towers.clear()
    }
    

    或者可能

    fn towers_attack(game: &mut Game) {
        game.towers.push(...)
    }
    

    这导致向量被重新分配,因此迭代器无效,这将导致坏事发生 .

    而是将您需要的项目子集传递给 towers_attack . 例如:

    fn towers_attack(lane_creeps: &mut Vec<Creeps>) { ... }
    

    我只需要将游戏的所有权交给塔和in mut game.towers {tower.towers_attack(&mut game)};

    always 将表达式的所有权转移到 for 循环 . 在这种情况下,您将可变引用的所有权传递给 towers .

    然后退出时归还所有权

    没有办法做到这一点; for 循环不返回任何内容 .

相关问题