如何将 Vec<Box<dyn Trait>> 移动到 Vec<Rc<RefCell<dyn Trait>>>

Nic*_*ick 5 casting traits rust

我有一个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但我得到了错误:

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

真的有可能还是我需要更改输入类型?

Sol*_*cko 1

虽然是 一种有效的类型,但由于allowedRefCell<dyn Trait>的声明,目前似乎没有一种方法可以从模块外部创建一个类型,除了,它需要从一个大小值开始。RefCell<T>T: ?SizedCoerceUnsized

但是,您应该能够使用unsafe代码转换为CellUnsafeCell,因为两者都有#[repr(transparent)].