1

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Max
  • 15,157
  • 17
  • 82
  • 127
  • 1
    Since you're implementing an ECS, have you watched [Catherine West's closing keynote from Rustconf this year](https://www.youtube.com/watch?v=aKLntZcp27M)? It's not super in-depth, but well worth 45 minutes in my opinion. – trent Sep 28 '18 at 02:31
  • Explicit returns at the end of the block are considered unidiomatic Rust. Just let the last expression be the return value (`fn name(&self) -> &'static str { "A" }`; `fn new(item: Box) -> Container { Container { item } }`, etc.). You can also avoid repeating yourself when constructing `Container` by only saying `item` once. – Shepmaster Sep 28 '18 at 02:36
  • You may find https://users.rust-lang.org/t/how-to-do-c-like-inheritance/20545 interesting – hellow Sep 28 '18 at 05:59

0 Answers0