Hello. I know inheritance is bad, but my purpose is different. I'm (still) writting a library which will provide a sealed element tree interface.
HTML elements are also sealed. If you think well of JS, you can't do this:
class Main extends HTMLDivElement {
// ....
}
new Main // Uncaught TypeError: Illegal constructor
Extending any DOM thing fails. It's like a specific type friendship. All classes from Node
to HTML elements have a inheritance friendship.
In particular I just want a simple tree where Drawable
is the sealed base of some objects, like Grid
, Rect
and Canvas
. It's easy and elegant to use traits for this. Note traits aren't meant for sealed trees; someone could easily extend the library drawables.
use Rf<O> = Rc<Cell<O>>;
pub use DrawableRef = Rf<Drawable>;
/// Trait for drawable objects.
///
pub trait Drawable {
fn draw(&mut self);
fn bounds(&mut self) -> &mut Bounds;
}
The issue is that calling #bounds()
in a random Rc<Cell<Drawable>>
would have a certain overhead. That's all my concern when using traits.
I'd like to be able to somehow have a base Drawable
struct, where its sub-types would Deref
to it and thus I could access bounds()
always directly. I've already used unsafe code for this purpose, but it's not elegant and, after all, I've to manually implement and call explicit cast methods (i.e., any_drawable.as_grid()
and any_grid.as_drawable()
).
If anyone has any better ideas than traits anyway, please tell me. Maybe these #bounds()
overheads might not be intensive.