[英]How to pass Rc<RefCell<dyn T>> to fn that wants &dyn T?
我無法將參數傳遞給 fn。
trait T {}
struct S {
others: Vec<Rc<RefCell<dyn T>>>
}
impl S {
fn bar(&self) {
for o in self.others {
foo(&o.borrow());
}
}
}
fn foo(t: &dyn T) {}
編譯器告訴我:
error[E0277]: the trait bound `std::cell::Ref<'_, (dyn T + 'static)>: T` is not satisfied
--> src/lib.rs:14:17
|
14 | foo(&o.borrow());
| ^^^^^^^^^^^ the trait `T` is not implemented for `std::cell::Ref<'_, (dyn T + 'static)>`
|
= note: required for the cast to the object type `dyn T`
我認為這就像 rust 書中的示例一樣,其中Rc
被自動取消引用,為了從 RefCell 中獲取值,我可以調用 borrow borrow()
。
我也嘗試過顯式取消引用,但似乎沒有任何效果。
如何為self
中的每個dyn T
object 調用foo()
?
正如錯誤所說, Ref<X>
不會自動實現X
實現的每個特征。 對於要強制為特征 object 的類型,它需要實現該特征。
您可以顯式取消引用Ref
,然后再次借用它:
impl S {
fn bar(&self) {
for o in &self.others {
foo(&*o.borrow());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.