I am trying to build a entity component system as part of my journey to learn Rust. I had an idea where each component would have a static id, and objects would have a HashMap of the components it contains (with the limit of one component per type).
Here is the object itself:
pub struct Object {
// TODO : components !
components: HashMap<i32, Box<dyn Component>>
}
impl Object {
pub fn add_component<C: Component>(&self) {
self.components.insert(C::id(), Box::new(C::new()));
}
pub fn get_component<C: Component>(&self) -> Option<&C> {
return self.components.get(C::id())
}
}
And here is my Component trait:
pub trait Component {
fn id() -> i32 {
// one must ensure this returns different id for every component
return 0;
}
fn new<C: Component>() -> C;
fn require_rendering(&self) -> bool {
return false;
}
fn some_function_on_component(&mut self) {
// do something on the component
}
}
Unfortunately, I get this error :
"this trait cannot be made into an object...
...because associated function id
has no self
parameter"
Could anyone explain why does this not work, and how to work around it?