Hi, I'm looking to that documentation: Using Trait Objects That Allow for Values of Different Types - The Rust Programming Language
I wrote all codes like that but I'm getting errors:
trait Draw {
fn draw(&self);
}
struct Button {
width: u32,
height: u32,
label: String,
}
impl Draw for Button {
fn draw(&self) {
println!(
"Button drawing, w: {}, h: {}, l: {}",
self.width, self.height, self.label
);
}
}
struct SelectBox {
width: u32,
height: u32,
options: Vec<String>,
}
impl Draw for SelectBox {
fn draw(&self) {
println!(
"SelectBox drawing, w: {}, h: {}, ops: {:?}",
self.width, self.height, self.options
);
}
}
struct Screen<T: Draw> {
components: Vec<Box<T>>,
}
impl<T> Screen<T>
where
T: Draw,
{
pub fn run(&self) {
for component in self.components.iter() {
component.draw();
}
}
}
fn main() {
let screen = Screen {
components: vec![
Box::new(SelectBox {
width: 75,
height: 10,
options: vec![
String::from("Yes"),
String::from("Maybe"),
String::from("No"),
],
}),
Box::new(Button {
width: 75,
height: 20,
label: String::from("OK"),
})
]
};
screen.run();
}
I'm getting that error:
error[E0308]: mismatched types
--> src/main.rs:64:18
|
64 | Box::new(Button {
| _________--------_^
| | |
| | arguments to this function are incorrect
65 | | width: 75,
66 | | height: 20,
67 | | label: String::from("OK"),
68 | | })
| |_________^ expected struct `SelectBox`, found struct `Button`
|
note: associated function defined here
For more information about this error, try `rustc --explain E0308`.
error: could not compile `my-project` due to previous error
exit status 101
I think it must work but I don't understand why I'm getting this error. What do you suggest? Thanks.