您如何将 Box<dyn Trait> 转换为 Rc<dyn Trait>?

问题描述

我有一个接收 Box<dyn Trait>函数,需要将其转换为 Rc<dyn Trait> 以在线程内共享只读所有权。

用一些 Box<T>T: Sized,我们可以做 Rc::new(*my_Box),但不幸的是 that doesn't work for unsized trait objects

这是一个过于简化的例子,希望能澄清问题:

use std::rc::Rc;

pub trait Trait {}

pub struct Foo {}
impl Trait for Foo {}

fn main() {
    let trait_Box: Box<dyn Trait> = Box::new(Foo {});
    let trait_rc: Rc<dyn Trait> = Rc::new(*trait_Box); // -> Error
}

Playground link

我看到 some things here and there 关于公开内部 RcBox支持BoxRc 之间移动,但 AFAIK 今天不可用。

是否有解决方法

或者,如果这种类型的转换是不可能的,那么推荐的存储特征对象的方法是什么,该对象可以突变到某个点,然后在该点之后与程序的其余部分不可变地共享?

>

当我知道我只有一个所有者时,使用 Rc<RefCell<dyn Trait>> 似乎有点矫枉过正......

解决方法

Rc<T> implements impl<T> From<Box<T,Global>> 所以你可以只使用 into:

let trait_rc: Rc<dyn Trait> = trait_box.into();

Permalink to the playground