Skip to content

Instantly share code, notes, and snippets.

@yongkyuns
Created July 3, 2020 16:03
Show Gist options
  • Save yongkyuns/e9d90316bbfb8898e3cc58a9f53b5a06 to your computer and use it in GitHub Desktop.
Save yongkyuns/e9d90316bbfb8898e3cc58a9f53b5a06 to your computer and use it in GitHub Desktop.
Trait Objects
trait Draw {
fn draw(&self);
}
struct Screen {
components: Vec<Box<dyn Draw>>,
}
impl Screen {
fn run(&self) {
for component in self.components.iter() {
component.draw();
}
}
}
struct Screen2<T: Draw> {
components: Vec<T>,
}
impl<T> Screen2<T>
where
T: Draw,
{
fn run(&self) {
for component in self.components.iter() {
component.draw();
}
}
}
struct Button {
width: u32,
height: u32,
label: String,
}
impl Draw for Button {
fn draw(&self) {
println!("Draw for Button called!");
}
}
struct SelectBox {
width: u32,
height: u32,
options: Vec<String>,
}
impl Draw for SelectBox {
fn draw(&self) {
println!("Draw for SelectBox called!");
}
}
fn main() {
let button = Box::new(Button {
width: 10,
height: 5,
label: String::from("Button"),
});
let select = Box::new(SelectBox {
width: 10,
height: 5,
options: vec![String::from("SelectBox")],
});
// let components = Vec
let screen = Screen {
components: vec![button, select],
};
screen.run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment