【发布时间】:2019-09-09 14:29:27
【问题描述】:
我的目标是将针对我的结构的方法调用委托给 Trait 的方法,其中 Trait 对象位于 Rc 的 RefCell 中。
我尝试遵循这个问题的建议: How can I obtain an &A reference from a Rc<RefCell<A>>?
我得到一个编译错误。
use std::rc::Rc;
use std::cell::RefCell;
use std::fmt::*;
use std::ops::Deref;
pub struct ShyObject {
pub association: Rc<RefCell<dyn Display>>
}
impl Deref for ShyObject {
type Target = dyn Display;
fn deref<'a>(&'a self) -> &(dyn Display + 'static) {
&*self.association.borrow()
}
}
fn main() {}
这是错误:
error[E0515]: cannot return value referencing temporary value
--> src/main.rs:13:9
|
13 | &*self.association.borrow()
| ^^-------------------------
| | |
| | temporary value created here
| returns a value referencing data owned by the current function
我的示例使用Display 作为特征;实际上,我有一个带有十几种方法的特征。我试图避免必须实现所有这些方法的样板,而只是在每次调用中深入到 Trait 对象。
【问题讨论】:
-
相关但可能不完全重复:How do I return a reference to something inside a RefCell without breaking encapsulation? 和 How to borrow the T from a RefCell<T> as a reference?。请注意,这两者都是通过实现
Deref的返回智能指针 的方法解决的,而不是简单地为主要类型实现Deref(在您的情况下为ShyObject)。