Trait objects at sub-classed widgets

Hello everyone,

I would like to store a trait object at my window struct (a subclassed adw::ApplicationWindow).

I have a MusicSource trait defined somewhere.

When I create a RefCell<Option<dyn MusicSource>> at the window struct (like all the other things and types I’ve successfully used packed inside a inside a RefCell<Option>> at the window struct) the compiler complains that:

error[E0277]: the size for values of type `(dyn MusicSource + 'static)` cannot be known at compilation time
   --> src/ui/window/imp.rs:33:23
    |
 33 |     pub music_source: RefCell<Option<dyn MusicSource>>,
    |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `Sized` is not implemented for `(dyn MusicSource + 'static)`
note: required by an implicit `Sized` bound in `std::option::Option`

Did anyone use trait objects at sub-classed widgets?

Thanks.

I don’t know what happened when I first tried to use a reference or a box together with a trait object, but it failed.

Now, however it works.

So the pretty easy solution to my problem was to just use a reference to a trait object or a boxed trait object like in this example:

RefCell<Option<'static dyn MusicSource>>

RefCell<Option<box<dyn MusicSource>>>

This is the suggested way to use trait objects by the way. See Using Trait Objects That Allow for Values of Different Types - The Rust Programming Language

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.