Skip to content

Instantly share code, notes, and snippets.

@ilopX
Created August 2, 2022 10:13
Show Gist options
  • Select an option

  • Save ilopX/260ac925b4a79abaa2c21e56f502408e to your computer and use it in GitHub Desktop.

Select an option

Save ilopX/260ac925b4a79abaa2c21e56f502408e to your computer and use it in GitHub Desktop.
fn main() {
let mut c = CompoundGraphics::new();
c.add_all(vec![
Box::new(Dot {
x: 100,
y: 200,
}),
Box::new(Rectangle {
x: 200,
y: 300,
width: 30,
height: 40,
}),
]);
c.draw();
}
trait Graphics {
fn moved(&mut self, x: i32, y: i32);
fn draw(&self);
}
struct CompoundGraphics<'a> {
children: Vec<Box<dyn Graphics + 'a>>,
}
impl<'a> CompoundGraphics<'a> {
fn new() -> Self {
Self {
children: Vec::new()
}
}
fn add_all(&mut self, shapes: Vec<Box<dyn Graphics>>) {
self.children.extend(shapes);
}
}
impl Graphics for CompoundGraphics<'_> {
fn moved(&mut self, _: i32, _: i32) {}
fn draw(&self) {
for child in &self.children {
child.draw();
}
}
}
struct Dot {
x: i32,
y: i32,
}
impl Graphics for Dot {
fn moved(&mut self, x: i32, y: i32) {
self.x = x;
self.y = y;
}
fn draw(&self) {
println!("Dot::draw(x: {}, y: {},)", self.x, self.y);
}
}
struct Rectangle {
x: i32,
y: i32,
width: i32,
height: i32,
}
impl Graphics for Rectangle {
fn moved(&mut self, x: i32, y: i32) {
self.x = x;
self.y = y;
}
fn draw(&self) {
println!(
"Rectangle::draw(x: {}, y: {}, width: {}, height:{})",
self.x, self.y, self.width, self.height
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment