繁体   English   中英

向下转换 Rc <refcell<box<struct> &gt;&gt; 到 Rc <refcell<box<dyn trait> &gt;&gt; </refcell<box<dyn></refcell<box<struct>

[英]Downcasting a Rc<RefCell<Box<struct>>> to Rc<RefCell<Box<dyn trait>>>

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

#[derive(Debug)]
pub struct Port<T: 'static + Copy + Debug> {
    pub name: String,
    values: Vec<T>,
}

这个结构实现了特征PortTrait 另一方面,我有以下结构

#[derive(Debug)]
pub struct Component {
    pub name: String,
    ports: HashMap<String, Rc<RefCell<Box<dyn PortTrait>>>>,
}

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

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时,编译时间会失败。

你知道有什么办法吗?

你需要摆脱Box

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

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

#[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
    }
}

游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM