Rc<RefCell<Dog>> to Rc<RefCell<dyn AnimalT>>

  1. I have:
let dog: Rc<RefCell<Dog>>;
// we also have, Dog : AnimalT
  1. How do we now create an object of type
let x: Rc<RefCell<AnimalT>>
  1. I have tried dog.clone() – it does not work :-/
1 Like

You could recreate the whole thing:

Rc::new(RefCell::new(dog.borrow().clone()))

In particular, Rc<RefCell<Dog>> cannot possibly be a subtype of Rc<RefCell<AnimalT>> because RefCell<T> is invariant in T due to mutability.

1 Like

Well it just work.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=2e70f0d278327bed50eaf2769e4eb8fe

Edit: It seems OP wants to remain the original dog usable, so I made a slightly modified version of it.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d1ca77556ac0b7f020fc4bbab90565a7

So why do we need another line for it? In rust we call it “Unsizing” to convert a pointer to constant sized type into a pointer to variable sized type, like [T] or dyn Trait. This cannot happen in generic context like other implicit coercions because after-coercion type can have conflicting trait impls with before-coercion type, so it’s possible to produce completely different code due to unwanted coercion if we don’t block it.

2 Likes

@Hyeonu : Thanks for pointing out my error. I clearly screwed up in creating the “minimal failure case” as it doesn’t fail. :slight_smile: