如何将 Rc<RefCell<dyn T>> 传递给需要 &dyn T 的 fn?

Dav*_*vid 2 dereference rust trait-objects interior-mutability

我无法将参数传递给 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) {}
Run Code Online (Sandbox Code Playgroud)

编译器告诉我:

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) {}
Run Code Online (Sandbox Code Playgroud)

我认为这就像在rust 书中的示例中,其中Rc自动取消引用并从我可以调用的 RefCell 中获取值borrow()

我也尝试过显式取消引用,但似乎没有任何效果。

如何调用foo()中的每个dyn T对象self

Pet*_*all 5

正如错误所说,Ref<X>不会自动实现实现的每个特征X。对于要强制转换为 trait 对象的类型,它需要实现该 trait。

您可以显式取消引用Ref,然后再次借用它:

impl S {
    fn bar(&self) {
        for o in &self.others {
            foo(&*o.borrow());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @David如果您确实需要“借用”,则可以显式使用“RefCell”:“foo(&amp;*RefCell::borrow(&amp;o))” (3认同)