微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决您如何将 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。