如果结构体的字段是私有的,是否可能将结构体的一部分作为可变的借用,另一部分作为不可变的借用。
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
引用仍然被借用。只有那部分不应该被借用吗?有没有办法强制执行这个规定?