I read Using Trait Objects That Allow for Values of Different Types - The Rust Programming Language
And I need to write something similar: a nested control tree.
I have some questions
- What would be the best way to avoid basic field duplication for all 'derived' controls?
- What would be the best way to implement basic methods for ControlTrait for all 'derived' controls? A macro?
- Is dynamic dispatch avoidable, looping through the children? Making it magically static? I guess each method (location(), size(), draw() etc. will be a dynamic call).
- What would be the best way to implement a parent ControlTrait to Control? Rc or Arc or lifetime reference field? (Locations of controls are relative to it's parent and probably we need the parent for other purposes as well).
Down here a simplified example
pub struct Point {
x: i32,
y: i32,
}
pub struct Size {
width: i32,
height: i32,
}
pub trait ControlTrait {
fn location(&self) -> Point;
fn size(&self) -> Size;
fn draw(&self);
}
// shared properties struct
pub struct Control {
location: Point,
size: Size,
children: Vec<Box<dyn ControlTrait >>
}
pub struct Button {
location: Point, // duplicated
size: Size, // duplicated
children: Vec<Box<dyn ControlTrait >>, // duplicated
text: String,
}