这是对Rust中游戏循环的一个非常简单的尝试:
trait Entity {
fn update(&mut self, world: &mut World);
}
struct World {
entities: Vec<Box<Entity>>
}
impl World {
fn update(&mut self) {
for ent in self.entities.iter_mut() {
ent.update(self);
}
}
}
然而,这不起作用:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> test.rs:12:16
|
11 | for ent in self.entities.iter_mut() {
| ------------- first mutable borrow occurs here
12 | ent.update(self);
| ^^^^ second mutable borrow occurs here
13 | }
| - first borrow ends here
error: aborting due to previous error
为了让实体脱离向量,我需要对World
结构进行可变借用,这会阻止实体以任何方式使用它。
构造它的好方法是什么,这样我既可以改变实体,也可以让实体引用世界上的其他对象(用于碰撞检查等)?
我能想到的唯一方法就是让实体返回自己的更新副本(我不认为分配和复制的所有内容都会对性能有好处)或者用unsafe
来反击