Is it possible to borrow parts of a struct as mutable and other parts as immutable?
You can only borrow the entire struct as immutable or mutable, there is no concept of borrowing only parts of it. When this becomes a problem, you can use interior mutability in the form of a RefCell
:
pub struct EntityComponentSystem {
entities: RefCell<HashMap<u64, Entity>>,
entities_with_components: HashMap<TypeId, HashSet<u64>>,
}
Now you can borrow the entire struct as immutable and borrow the contents of the RefCell
independently as mutable:
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
}