我有下面的结构。它只是给定数据类型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>>>>,
}组件共享端口以进行通信。我想使用一种方法来创建一个新的端口( 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时,这将在编译时失败。
你知道怎么做吗?
发布于 2022-07-31 08:07:04
你需要摆脱Box。
问题是我们分配了Rc<RefCell<Box<Port<T>>>>。Box<Port<T>>的大小为1 usize,但现在您希望将其转换为具有2 usizes大小的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
}
}游乐场。
https://stackoverflow.com/questions/73179036
复制相似问题