是否可以借用结构体的一部分作为可变的而其他部分作为不可变的?

2023-11-24

如果结构体的字段是私有的,是否可以借用结构体的一部分作为可变的,而另一部分作为不可变的。

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

我不明白的是,&self参考文献get_entities_with_component在我们基本上归还了一部分之后仍然是借来的entities_with_components field.

不是应该只借那部分吗?有什么办法可以强制执行吗?


您只能借用entirestruct 是不可变或可变的,不存在仅借用其中一部分的概念。当这成为问题时,您可以使用内部可变性以一个形式RefCell:

pub struct EntityComponentSystem {
    entities: RefCell<HashMap<u64, Entity>>,
    entities_with_components: HashMap<TypeId, HashSet<u64>>,
}

现在您可以借用整个结构作为不可变的并借用该结构的内容RefCell独立地作为可变的:

pub fn get_mut_components(&self, entity_id: u64) -> &mut TypeMap {
    let mut entities = self.entities.borrow_mut();
    let entity = entities.get_mut(&entity_id).unwrap();
    &mut entity.components
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以借用结构体的一部分作为可变的而其他部分作为不可变的? 的相关文章

随机推荐