Hi evryone,
after having great feelings of success with learning Rust I'm currently got stucked into the following problem:
Given an API which takes a trait object by reference (&dyn ...
), is it possible to put this reference into a collection with boxed trait objects (Box<dyn ...>
)? The following example fails if uncommented with the described compiler message because it's not possible to deref unsized trait references. If I understood it right it's easy to convert a box into a &
by calling box.as_ref()
so how to do it vice versa?
pub trait Node {}
pub struct ExampleNode {
}
impl Node for ExampleNode {
}
pub struct Container {
children: Vec<Box<dyn Node>>,
}
impl Container {
pub fn add_node(&mut self, t: &dyn Node) {
// let b: Box<dyn Node> = Box::new(*t); // ^^^^^^^^ doesn't have a size
// self.children.push(b); // known at compile-time
}
}
fn main() {
let mut container = Container{children: Vec::new()};
container.add_node(&ExampleNode{});
}