Better alternative to `Rc<Box<T>>`?


#1

I had a trait object Box<T>, which I at first intended to keep references to within a struct, with a manual lifetime. However, the lifetimes just aren’t really working, and while I’m planning to come back to it, I changed it to Rc<T>, so I could just share it easily for now.

However, it turns out Rc can’t contain a trait object? Is there for a reason for this, and is there a better pattern to use apart from Rc<Box<T>>? Thanks!


#2

It can, and you can use coercion to assign this:

let rc: Rc<fmt::Debug> = Rc::new(42);

The value on the right side here is Rc<i32>, which is then coerced to the trait object type.


#3

Ah, so you can! Thanks very much


#4

In case you didn’t know, you can also write it with as:

let rc = Rc::new(42) as  Rc<fmt::Debug>;

Usually, though, type inference will pick up on the fact that it’s meant to be a trait object.


#5

also, this latter form is frowned upon by the trivial_casts lint in the compiler.