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.

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

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:

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