Downcast to a trait

Suppose I've TabBar → Control → DisplayObject.

This line doesn't work:

println!("{}", Rc::downcast::<dyn Control>(o).unwrap().x()); // 64

I get:

error[E0277]: the size for values of type `dyn Control` cannot be known at compilation time
    --> src/
26   |     println!("{}", Rc::downcast::<dyn Control>(o).unwrap().x()); // 64
     |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time

You can only use Rc::downcast to get back the original type TabBar. You can't downcast to a trait object.

From the other topic:

Falliable downcasting to base types is about all you can do with dyn Any; you probably want to carry around a dyn Control directly (in which case, you don't need to downcast to use the functionality of the Control trait -- and not the DisplayObject trait either, since it is a supertrait of Control).

The problem is that Control would be declared in an external crate that overrides another crate's declarations; in the case, crate a) would extend crate b) DisplayObject. The crate b) would use Rc<dyn DisplayObject> in several places, which won't cast to Rc<dyn Control>. The crate b) doesn't have idea that Control from crate a) exists.

Using as_dyn_display_object, crate a) can use Rc<Control> and convert to an Rc<DisplayObject> to interact with crate b) as needed. (But this may still not be what you want; crate b) won't call crate a)'s Control implementation.)

Additionally, I think you'll find method overriding to be a poor fit for Rust in general.

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.