Can't use traits for one-level hierarchy

I've a simple, closed-set of implementors, like:

  • DisplayObject — trait
    • Container — struct
    • MovieClip — struct
    • Image — struct
    • More

The goal is to have 2D hierarchical nodes which implement rendering and share a lot of common properties (through a common() required method, used for other optional methods).

I had, however, given up in using this hierarchy because I got some Rc specific up/downcasting issues. I think I specifically run into some limitation with Rc<dyn DisplayObject>. Perhaps I was about to use a generic and forgot the ?Sized constraint, but not sure...

So I'm actually almost about to settle down with composition using a struct and an enum, but I honestly preferred traits except when it comes to PartialEq and Hash applied to DisplayObject references.

Since all the implementors are known, I think an enum which implements DisplayObject by deferring to the DisplayObject implementations of the enum variants (with match self and whatnot) would be preferable to dyn DisplayObject. I think there’s an enum-dispatch crate for doing something like that, though personally I just make a small ad-hoc macro_rules! macro to handle the repetitive boilerplate.

2 Likes

I see, so it's normal to do what I do, I guess!

I didn't understand this enum-dispatch crate though, but I'm fine going with a match for specific behaviours.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.