[英]How to pass Rc<RefCell<dyn T>> to fn that wants &dyn T?
I have trouble passing an argument to a fn.我无法将参数传递给 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) {}
The compiler tells me:编译器告诉我:
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`
I thought this was like in the example in the rust book, where the Rc
is auto dereferenced and to get the value out of the RefCell I could call borrow()
.我认为这就像 rust 书中的示例一样,其中
Rc
被自动取消引用,为了从 RefCell 中获取值,我可以调用 borrow borrow()
。
I tried explicit dereferencing too, but nothing seems to work.我也尝试过显式取消引用,但似乎没有任何效果。
How can I call foo()
for each dyn T
object in self
?如何为
self
中的每个dyn T
object 调用foo()
?
As the error says, Ref<X>
does not automatically implement every trait that X
implements.正如错误所说,
Ref<X>
不会自动实现X
实现的每个特征。 For a type to be coerced to a trait object, it needs to implement that trait.对于要强制为特征 object 的类型,它需要实现该特征。
You can explicitly dereference the Ref
and then borrow it again:您可以显式取消引用
Ref
,然后再次借用它:
impl S {
fn bar(&self) {
for o in &self.others {
foo(&*o.borrow());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.