You can't. RefCell::borrow
returns a Ref<T>
, not a &T
. If you try to do this in a method then you will need to first borrow the Ref<T>
but it will go out of scope.
Instead of implementing Deref
, you could have a method that returns something that does:
impl ShyObject {
fn as_deref(&self) -> impl Deref<Target = dyn Display> {
self.association.borrow()
}
}
Otherwise, since you only want to expose the Display
implementation of the inner data anyway, you can workaround it by actually dereferencing a different type which delegates:
pub struct ShyObject {
association: Assocation<dyn Display>,
}
struct Assocation<T: ?Sized>(Rc<RefCell<T>>);
impl<T: Display + ?Sized> fmt::Display for Assocation<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0.borrow())
}
}
impl Deref for ShyObject {
type Target = dyn Display + 'static;
fn deref(&self) -> &Self::Target {
&self.association
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…