1

I have a trait MyTrait and a struct MyStruct that implements MyTrait.

I also have a function that accepts Rc<RefCell<Box<MyTrait>>> as an argument.

Somewhere in the code I create an instance of Rc<RefCell<Box<MyStruct>>>:

let my_struct = Rc::new(RefCell::new(Box::new(MyStruct)));

When I pass my_struct to my function I get a compiler error:

error: mismatched types: expected alloc::rc::Rc<core::cell::RefCell<Box<MyTrait>>>, found alloc::rc::Rc<core::cell::RefCell<Box<MyStruct>>>

I try to fix that by creating an instance of Rc<RefCell<Box<MyStruct>>> by explicitly specifying the type I need:

let my_struct: Rc<RefCell<Box<MyTrait>>> = Rc::new(RefCell::new(Box::new(MyStruct)));

In this case passing my_struct to my function works fine, however I can't access any MyStruct specific fields via my_struct variable anymore. And it doesn't seem to be a way to cast down Rc<RefCell<Box<MyTrait>>> to Rc<RefCell<Box<MyStruct>>>.

How can I go around this problem?

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
Dmitry Uvarov
  • 673
  • 6
  • 6
  • A `Box` is known as a *trait object* (your extra layers of `Rc` and `RefCell` are extraneous and you should have removed them as part of creating an [MCVE](/help/mcve)). You also were **super** close with the right keywords, but it's more commonly referred to as *downcasting* as opposed to *casting down*. – Shepmaster Jun 15 '15 at 22:58
  • 2
    Thanks for your reply. Please note, that my question was explicitly about Rc>> as I need referenced-counted pointer with mutability. If I used just Rc or Box I wouldn't have any problem. I would just create an instance of `Rc`: `let my_struct: Rc = Rc::new(MyStruct)` and then pass it to the function that accepts `Rc` and that would worked just fine. The problem happens when I add this extra RefCell bit and that's what I wanted to highlight in my question. – Dmitry Uvarov Jun 16 '15 at 07:04

0 Answers0