Why is the example in the book changed to generic and the prompt type does not match?
https://doc.rust-lang.org/book/ch17-02-trait-objects.html
Complete Code:
lib.rs
pub trait Draw {
fn draw(&self);
}
// pub struct Screen {
// pub components: Vec<Box<dyn Draw>>,
// }
pub struct Screen<T: Draw> {
pub components: Vec<T>,
}
// impl Screen {
impl<T> Screen<T> where T: Draw {
pub fn run(&self) {
for component in self.components.iter() {
component.draw();
}
}
}
pub struct Button {
pub width: u32,
pub height: u32,
pub label: String,
}
impl Draw for Button {
fn draw(&self) {
println!("draw Button width: {} height: {} label: {}",
self.width, self.height, self.label);
}
}
pub struct SelectBox {
pub width: u32,
pub height: u32,
pub options: Vec<String>,
}
impl Draw for SelectBox {
fn draw(&self) {
println!("draw SelectBox width: {} height: {} \
options: {:?}",
self.width, self.height, self.options);
}
}
main.rs
mod lib;
use lib::{Screen, Button, SelectBox};
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: 50,
height: 10,
label: String::from("OK"),
}
),
]
};
screen.run();
}
The compilation error is as follows:
error[E0308]: mismatched types
--> src\main.rs:17:17
|
17 | / Button {
18 | | width: 50,
19 | | height: 10,
20 | | label: String::from("OK"),
21 | | }
| |_________________^ expected struct `SelectBox`, found struct `Button`