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

标签 casting rust traits

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

相关文章:

php - 我可以使用什么设计模式来模拟 PHP 中的特征/混合?

c++ - 由 traits [policies, actually] 实例化的类成员函数

casting - Seq.cast 元组值从 obj 到字符串

c - 如何从 char[4] 生成 int? (在 C 中)

rust - `while let Ok(t) ... = try_read!(...)` 使读取循环更整洁

rust - 在方法中使用特征和泛型的 Rust 语法是什么?

c++ - 在 C++ 2017 中将 const 转换为非常量指针并对其进行修改时,编译器将这两个值存储在哪里?

c# - 使用 "as"关键字转换对象返回 null

rust - 如何在 Rust FFI 中发布常量字符串?

Rust 类型不匹配解决 `for<' r> ...` 带有闭包特征别名参数