【发布时间】:2020-05-23 17:47:43
【问题描述】:
我有一个Vec<Box<dyn Trait>> 作为输入,我想将它的元素存储在Vec<Rc<RefCell<dyn Trait>>> 中。最好的方法是什么?
我试过了:
use std::cell::RefCell;
use std::rc::Rc;
trait Trait {}
fn main() {
let mut source: Vec<Box<dyn Trait>> = Vec::new();
let mut dest: Vec<Rc<RefCell<dyn Trait>>> = Vec::new();
for s in source {
let d = Rc::new(RefCell::new(s.as_ref()));
dest.push(d);
}
}
但我得到了错误:
error[E0277]: the trait bound `&dyn Trait: Trait` is not satisfied
--> src/main.rs:12:19
|
12 | dest.push(d);
| ^ the trait `Trait` is not implemented for `&dyn Trait`
|
= note: required for the cast to the object type `dyn Trait`
是否真的可以或我需要更改输入类型?
【问题讨论】:
-
问题不在于转换,而是
RefCell需要拥有它的数据,所以你根本无法构造RefCell<dyn Trait>。您需要将类型更改为Vec<Rc<RefCell<Box<dyn Trait>>>> -
甚至
Vec<Box<RefCell<dyn Trait>>>,我看到有转换Rc::from<T>(Box<T>)。