如何将Vec >移到Vec >>

问题描述 投票:4回答:2

我有一个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`

实际上是否可能,或者我是否需要更改输入类型?

casting rust traits
2个回答
1
投票

尽管RefCell<dyn Trait>是有效类型,但是由于RefCell<T>的声明允许RefCell<T>,所以目前似乎没有一种方法可以从模块外部创建一个模块,但T: ?Sized除外,这需要以大小值。


0
投票

如果控制Cell,一种选择是通过遵从内部实现,简单地为UnsafeCell实现它:

© www.soinside.com 2019 - 2024. All rights reserved.