[英]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.