I'm learning Rust trying to make something like an ECS (Entity Component System)
I have a struct of multiple HashMaps for each component and I need to call HashMap::new()
, remove_entry()
and insert()
on each field:
struct Components {
component_a: HashMap<EntityId, DataA>,
component_b: HashMap<EntityId, DataB>,
component_c: HashMap<EntityId, DataC>,
component_d: HashMap<EntityId, DataD>,
component_e: HashMap<EntityId, DataE>,
}
impl Components {
fn new() -> Self {
Self {
component_a: HashMap::new(),
component_b: HashMap::new(),
component_c: HashMap::new(),
component_d: HashMap::new(),
component_e: HashMap::new(),
}
}
fn remove_entity(&mut self, entity: EntityId) {
self.component_a.remove_entry(&entity);
self.component_b.remove_entry(&entity);
self.component_c.remove_entry(&entity);
self.component_d.remove_entry(&entity);
self.component_e.remove_entry(&entity);
}
fn add_entity(&mut self, entity: EntityBuilder) {
match entity.component_a {
Some(data) => self.component_a.insert(entity.entity_id, data),
None => None,
};
match entity.component_b {
Some(data) => self.component_b.insert(entity.entity_id, data),
None => None,
};
match entity.component_c {
Some(data) => self.component_c.insert(entity.entity_id, data),
None => None,
};
match entity.component_d {
Some(data) => self.component_d.insert(entity.entity_id, data),
None => None,
};
match entity.component_e {
Some(data) => self.component_e.insert(entity.entity_id, data),
None => None,
};
}
}
This can get out of hand pretty quickly as the number of components scale, so my questiion is:
How can I call a function on every field of the struct?
I'd like it to be something like this: call_function!(remove_entry(&entity)))
and call_function!(insert(&entity)))
is this any good?