I have a bunch of types:
struct A { cool_thing: &'static str }
struct B {}
struct C {}
struct D {}
I also have a way of identifying the types, e.g.
trait Name {
fn name(&self) -> &'static str;
}
impl Name for A {
fn name(&self) -> &'static str { return "A"; }
}
// etc.
Given the above, what is the best way to implement a container for these types? For instance, I want something like this:
struct Container {
item: Box<Name>,
}
impl Container {
fn new(item: Box<Name>) -> Container {
return Container { item: item };
}
fn get_item(&self) -> &Name {
return self.item.as_ref();
}
}
Later, I'd like to use this container:
let a = A { cool_thing: "Yah!" };
let container = Container::new(Box::new(a));
let thing = container.get_item();
if thing.name == "A" {
// How to access cool_thing here?
}
How can this be accomplished?
I'd like Container
to be able to store objects without depending on them explicitly. This is to avoid possible circular dependencies where an object might want to consume a Container
as well as populate it with some local type (specifically I'm trying to implement the "entity" of an entity-component-system. The dependency issue makes using something like an enum inappropriate.