【发布时间】:2018-02-02 04:09:49
【问题描述】:
如果结构的字段是私有的,是否可以将结构的一部分借用为可变的,而将另一部分借用为不可变的。
fn main() {
let mut ecs = EntityComponentSystem::new();
for e_id in ecs.get_entities_with_component::<Velocity>().unwrap() {
let components = ecs.get_mut_components(e_id);
...
}
impl EntityComponentSystem {
...
pub fn get_entities_with_component<K: Key>(&self) -> Option<&HashSet<u64>> {
self.entities_with_components.get(&TypeId::of::<K>())
}
pub fn get_mut_components(&mut self, entity_id: u64) -> &mut TypeMap {
let entity = self.entities.get_mut(&entity_id).unwrap();
&mut entity.components
}
}
pub struct EntityComponentSystem {
entities: HashMap<u64, Entity>, <------- I would like to modify this.
entities_with_components: HashMap<TypeId, HashSet<u64>>, <---- while reading from this!
}
编译器给了我:
error[E0502]: cannot borrow `*ecs` as mutable because it is also borrowed as immutable
--> physics.rs:19:26
|
18 | for e_id in ecs.get_entities_with_component::<Velocity>() {
| --- immutable borrow occurs here
19 | let components = ecs.get_mut_components(*e_id);
| ^^^ mutable borrow occurs here
...
26 | }
| - immutable borrow ends here
我不明白的是,在我们基本上返回了 entities_with_components 字段的一部分之后,get_entities_with_component 中的 &self 引用仍然是如何被借用的。
不应该只借那部分吗?有什么办法可以强制执行吗?
【问题讨论】:
标签: rust borrow-checker