[英]Downcasting a Rc<RefCell<Box<struct>>> to Rc<RefCell<Box<dyn trait>>>
I have the following struct.我有以下结构。 It is just a wrapper for a vector of a given data type
T
:它只是给定数据类型
T
的向量的包装器:
#[derive(Debug)]
pub struct Port<T: 'static + Copy + Debug> {
pub name: String,
values: Vec<T>,
}
This structure implements the trait PortTrait
.这个结构实现了特征
PortTrait
。 On the other hand, I have the following structure另一方面,我有以下结构
#[derive(Debug)]
pub struct Component {
pub name: String,
ports: HashMap<String, Rc<RefCell<Box<dyn PortTrait>>>>,
}
Components share ports to communicate.组件共享端口进行通信。 I want to use a method to i) create a new port
Port<T>
, ii) add this new port to the component, and iii) return a pointer to the newly created port.我想使用一种方法来 i)创建一个新端口
Port<T>
,ii)将此新端口添加到组件中,以及 iii)返回一个指向新创建端口的指针。 So far, I got this:到目前为止,我得到了这个:
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
}
}
This fails in compilation time when trying to downcast the clone of the port to a dyn PortInterface
.当尝试将端口的克隆向下转换为
dyn PortInterface
时,编译时间会失败。
Do you know any way to do this?你知道有什么办法吗?
You need to get rid of the Box
.你需要摆脱
Box
。
The problem is that we allocated Rc<RefCell<Box<Port<T>>>>
.问题是我们分配了
Rc<RefCell<Box<Port<T>>>>
。 Box<Port<T>>
has a size of 1 usize
, but now you want to convert it to Box<dyn PortTrait>
which has size of 2 usize
s - but there is no place in the Rc
to store it! Box<Port<T>>
的大小为 1 usize
,但现在您想将其转换为大小为 2 usize
s 的Box<dyn PortTrait>
- 但Rc
中没有地方存储它!
Luckily, you don't need Box
: Rc<RefCell<dyn Trait>>
works just fine.幸运的是,您不需要
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
}
}
Playground . 游乐场。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.