![](/img/trans.png)
[英]How to move a Vec<Box<dyn Trait>> Into Vec<Rc<RefCell<dyn Trait>>>
[英]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.