首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将Rc<RefCell<Box<struct>>>下播到Rc<RefCell<Box<dyn trait>>>

将Rc<RefCell<Box<struct>>>下播到Rc<RefCell<Box<dyn trait>>>
EN

Stack Overflow用户
提问于 2022-07-30 21:02:58
回答 1查看 42关注 0票数 0

我有下面的结构。它只是给定数据类型T的向量的包装器。

代码语言:javascript
复制
#[derive(Debug)]
pub struct Port<T: 'static + Copy + Debug> {
    pub name: String,
    values: Vec<T>,
}

该结构实现了特征PortTrait。另一方面,我有以下的结构

代码语言:javascript
复制
#[derive(Debug)]
pub struct Component {
    pub name: String,
    ports: HashMap<String, Rc<RefCell<Box<dyn PortTrait>>>>,
}

组件共享端口以进行通信。我想使用一种方法来创建一个新的端口( Port<T> ),( ii)将这个新端口添加到组件中,以及( iii)返回指向新创建端口的指针。到目前为止,我知道了:

代码语言:javascript
复制
impl Component {
    fn add_in_port<T: 'static + Copy + Debug>(&mut self, port_name: &str) -> RcCell<Box<Port<T>>> {
        let port = RcCell::new(Box::new(Port::<T>::new(port_name)));
        let x: RcCell<Box<dyn PortTrait>> = RcCell::clone(&port); // this fails
        self.ports.insert(port_name.to_string(), x);
        port
    }
}

当试图将端口的克隆降为dyn PortInterface时,这将在编译时失败。

你知道怎么做吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-31 08:07:04

你需要摆脱Box

问题是我们分配了Rc<RefCell<Box<Port<T>>>>Box<Port<T>>的大小为1 usize,但现在您希望将其转换为具有2 usizes大小的Box<dyn PortTrait> --但是Rc中没有存储它的位置!

幸运的是,您不需要BoxRc<RefCell<dyn Trait>>工作得很好。

代码语言:javascript
复制
#[derive(Debug)]
pub struct Component {
    pub name: String,
    ports: HashMap<String, Rc<RefCell<dyn PortTrait>>>,
}

impl Component {
    fn add_in_port<T: 'static + Copy + Debug>(&mut self, port_name: &str) -> Rc<RefCell<Port<T>>> {
        let port = Rc::new(RefCell::new(Port::<T>::new(port_name)));
        let x = Rc::clone(&port) as Rc<RefCell<dyn PortTrait>>;
        self.ports.insert(port_name.to_string(), x);
        port
    }
}

游乐场

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73179036

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档