Rc<RefCell<X: FooBarT>> -> Rc<RefCell<dyn FooBarT>>

We have:

struct X;
trait FooBarT:
X: FooBarT;

obj: Rc<RefCell<X>>;

X does not implement Copy

Now, is it possible to simultaneously have:

obj: Rc<RefCell<X>>;
obj2: Rc<RefCell<dyn FooBarT>>;


I'm not sure what the question is. Is this code useful?

1 Like
type Obj = Rc<RefCell<X>>;
type Obj2 = Rc<RefCell<dyn FooBarT>>;

fn main() {
    let obj1: Obj = Rc::new(RefCell::new(X));
    let obj2: Obj2 = Rc::clone(&obj1) as _;

is really helpful. I didn't realize you could just cast it via the as

So in particular, X as FooBarT doesn't surprise me, but the fact that we can do

Rc<RefCell<X>> as Rc<RefCell<FooBarT>> is surprising to me.

Implicit coercion (without as) also works with Obj::clone(&obj) or obj.clone(). The bare Rc::clone seems to infer Obj2::clone instead, which doesn't work for the full chain of unsized coercion.

See also: https://doc.rust-lang.org/std/ops/trait.CoerceUnsized.html