Why can't a Rc which takes ownership of self have ownership taken in a trait w/ predefined body?
⚓ Rust 📅 2025-12-28 👤 surdeus 👁️ 5Hello. I'm writing an application which makes heavy use of traits and Reference Counters (std::rc::Rc). I have several structs/impl's I only wanted accessed via a Rc (so they may be "passed around" and borrowed easily. These structs which I only want wrapped in an Rc are then wrapped into another struct with some utility methods to make accessing/borrowing easier.
Consider this code segment:
struct RcWrapped{
...
value: Rc<RefCell<dyn RcWrappable>>
}
impl RcWrapped{
fn from_rc(value: Rc<RefCell<dyn RcWrappable>>) -> RcWrapped{
RcWrapped{
value,
..Default::default()
}
}
}
struct CoolStruct{
...
}
// POSSIBLE IMPLEMENTATIONS:
// IMPLEMENTATION A:
impl RcWrappable for CoolStruct;
trait RcWrappable{
fn to_rc(self) -> RcWrapped
where Self: Sized {
RcWrapped::from_rc(Rc::new(RefCell::new(self)))
}
}
OR
// IMPLEMENTATION B:
impl CoolStruct{
fn to_rc(self) -> RcWrapped{
RcWrapped::from_rc(Rc::new(RefCell::new(self)))
}
}
Look closely, implementation B works just fine. However, I would rather not reuse the same method over and over again, cluttering every implementation of a RcWrappable struct.
Implementation A doesn't work. I get an error saying Self may not live long enough. How can this even matter? RcWrapped owns self through Rc and RefCell in both cases. Self now lives as long as the returned RcWrapped value which is all we need.
Why does the compiler error here? Is one way more valid than the other? Is this even a good approach?
The idea is that I could just write
impl RcWrappable for ... on any struct I want to be easily wrappable into the RcWrapped type.
11 posts - 5 participants
🏷️ Rust_feed