我在传递参数给函数时遇到了问题。
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()
。我也尝试了显式解引用,但是似乎没有用。
如何在
self
中为每个dyn T
对象调用foo()
?
Borrow
,您可以显式地使用RefCell
版本:foo(&*RefCell::borrow(&o))
。 - trent