[英]How do you convert a Box<dyn Trait> to a Rc<dyn Trait>?
I have a function which receives a Box<dyn Trait>
and needs to convert that into an Rc<dyn Trait>
to share read-only ownership within the thread.我有一个 function 接收
Box<dyn Trait>
并需要将其转换为Rc<dyn Trait>
以在线程内共享只读所有权。
With a Box<T>
of some T: Sized
, we can do Rc::new(*my_box)
, but unfortunately that doesn't work for unsized trait objects .使用某个
T: Sized
的Box<T>
,我们可以执行Rc::new(*my_box)
,但不幸的是,这不适用于 unsized trait objects 。
Here's an oversimplified example which hopefully clarifies the problem:这是一个过于简化的示例,希望可以澄清问题:
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
}
I saw some things here and there about exposing the internal RcBox
to support moving between Box
and Rc
, but AFAIK it's not usable today.我在这里和那里看到了一些关于暴露内部
RcBox
以支持在Box
和Rc
之间移动的事情,但是 AFAIK 今天它不可用。
Is there a workaround for this?有解决方法吗?
Or if this type of conversion isn't possible, what is the recommended method for storing a trait object which can be mutated up to a point, and then after that point be shared immutably with the rest of the program?或者,如果这种类型的转换是不可能的,那么推荐的存储特征 object 的方法是什么,该特征可以突变到一个点,然后在该点之后与程序的 rest 不可改变地共享?
Using a Rc<RefCell<dyn Trait>>
seems like overkill when I know I just have a single owner up to that point...当我知道到目前为止我只有一个所有者时,使用
Rc<RefCell<dyn Trait>>
似乎有点矫枉过正......
Rc<T>
implements impl<T> From<Box<T, Global>>
so you can just use into
: Rc<T>
实现了impl<T> From<Box<T, Global>>
所以你可以使用into
:
let trait_rc: Rc<dyn Trait> = trait_box.into();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.