我有一个 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<dyn Trait>
是一个有效的类型,因为 RefCell<T>
的声明允许 T: ?Sized
,目前似乎没有一种方法可以从模块外部创建一个,除了 CoerceUnsized
,这需要从一个大小的值开始。
但是,您应该可以使用 unsafe
转换为 Cell
的代码或 UnsafeCell
, 因为两者都有 #[repr(transparent)]
.
关于casting - 如何将 Vec<Box<dyn Trait>> 移动到 Vec<Rc<RefCell<dyn Trait>>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61976226/