【发布时间】:2021-08-24 20:03:58
【问题描述】:
好的,我有Combatants 与Battlefield 战斗。我对在哪个地方发生的事情的直觉有点偏离。它非常接近成为一个游戏,但我现在卡住了。
我希望Battlefield 有一个tick() 功能,它允许所有Combatants 做出决定,例如攻击对方的另一支队伍,或者在没有人在范围内时靠近一个队伍。我在让借阅检查员对此感到满意时遇到了问题。
这是一个包含我的代码所有问题的最小版本。
struct Combatant{
current_health: i16,
max_health: i16
}
struct Battlefield{
combatants: Vec<Combatant>
}
impl Combatant {
fn attack(&self, other: &mut Combatant) {
other.current_health -= 3;
}
}
impl Battlefield {
fn tick(&mut self) {
let target = &mut self.combatants[0];
for combatant in &self.combatants {
combatant.attack(target);
}
}
}
cargo check 返回
error[E0502]: cannot borrow `self.combatants` as immutable because it is also borrowed as mutable
--> src/main.rs:20:26
|
19 | let target = &mut self.combatants[0];
| --------------- mutable borrow occurs here
20 | for combatant in &self.combatants {
| ^^^^^^^^^^^^^^^^ immutable borrow occurs here
21 | combatant.attack(target);
| ------ mutable borrow later used here
我如何设计这个函数(或者更像是整个场景,呵呵)让它在 Rust 中工作?
【问题讨论】:
-
看看像 hecs 或 specs 这样的 ECS 库,在这些基础上构建类似游戏的应用程序逻辑通常要容易得多。
-
是的,我之前使用过 Bevy。我这样做是为了挑战自己,也许会从中得到一些乐趣作为副作用。
标签: rust borrow-checker