How to push a Box<dyn Trait> into a Vec<Rc<RefCell<dyn Trait>>>

Hi everyone,

I would like to push a Box<dyn Trait> into a Vec<Rc<RefCell<dyn Trait>>>.

Here I manage to I would like to push a Box<dyn Trait> into a Vec<Rc<dyn Trait>> using the method Rc::from.

What is the better way to create a new Rc<RefCell<dyn Trait>> from a already instantied Box<dyn Trait> without downcast or clone.

Can you help me please?

I don't think it is possible to wrap it in a RefCell after you have done the conversion from Box<TheActualType> to Box<dyn Trait>.

One exception is if you control the trait, because then you can convert backwards to Box<TheActualType> and do the conversion. To do this, define a helper trait:

trait HelperTrait {
    fn wrap_in_refcell(self: Box<Self>) -> Rc<RefCell<dyn MyTrait>>;
}
impl<T: MyTrait + 'static> HelperTrait for T {
    fn wrap_in_refcell(self: Box<Self>) -> Rc<RefCell<dyn MyTrait>> {
        Rc::new(RefCell::new(*self))
    }
}

and add it as a sub-trait to your trait:

trait MyTrait: HelperTrait {
    ...
}

playground

4 Likes

Thanks a lot @alice

This seems to be a good solution.

Even if I do not yet understand why it is necessary to resort to the definition of a HelperTrait .

Playground

Generally the reason is that RefCell<dyn Trait> is a kinda half-baked feature, so the ways to create it are limited.

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.