[英]How can I consume data type of Rc<RefCell<T>> in struct?
[英]How can I implement Deref for a struct that holds an Rc<Refcell<Trait>>?
我的目標是將針對我的結構的方法調用委托給Trait的方法,其中Trait對象位於RefCell
的Rc
中。
我試圖遵循以下問題的建議: 如何從Rc <RefCell <A >>獲取&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對象。
你不能 RefCell::borrow
返回Ref<T>
,而不是&T
。 如果嘗試使用方法來執行此操作,則需要首先借用Ref<T>
但它會超出范圍。
除了實現Deref
,您還可以使用一個方法返回執行Deref
的方法:
impl ShyObject {
fn as_deref(&self) -> impl Deref<Target = dyn Display> {
self.association.borrow()
}
}
否則,由於無論如何您只想公開內部數據的Display
實現,因此可以通過實際取消引用委托的其他類型來解決此問題:
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.