Skip to content

Instantly share code, notes, and snippets.

@yongkyuns
Created July 14, 2020 13:58
Show Gist options
  • Save yongkyuns/a87b8374435032e21492274db03e5024 to your computer and use it in GitHub Desktop.
Save yongkyuns/a87b8374435032e21492274db03e5024 to your computer and use it in GitHub Desktop.
Drawable Example
use crate::draw::Draw;
use std::cell::Cell;
use std::cell::RefCell;
use std::rc::Rc;
pub trait Drawable {
fn add_line(&mut self) -> &mut dyn Drawable;
fn shift(&mut self, x: f32, y: f32) -> &mut dyn Drawable;
}
#[derive(Debug, Clone, Copy)]
pub struct Point {
x: f32,
y: f32,
}
impl Point {
pub fn new() -> Self {
Point { x: 0., y: 0. }
}
}
#[derive(Debug)]
pub struct Line {
points: Vec<Point>,
}
impl Line {
pub fn new() -> Self {
let points = Vec::new();
Line { points }
}
pub fn add(&mut self, point: Point) {
// self.points.borrow_mut().push(point);
self.points.push(point);
}
}
#[derive(Debug)]
pub struct Rect {
lines: Vec<Line>,
}
impl Rect {
pub fn new() -> Self {
let lines = Vec::new();
Rect { lines }
}
pub fn add(&mut self, line: Line) {
self.lines.push(line);
}
}
impl Drawable for Rect {
fn add_line(&mut self) -> &mut dyn Drawable {
println!("Drawing Rect!");
self.lines.push(Line {
points: vec![Point { x: 50., y: 50. }, Point { x: 70., y: 70. }],
});
self
}
fn shift(&mut self, x: f32, y: f32) -> &mut dyn Drawable {
println!("Shifting Rect!");
for line in &mut self.lines {
for pt in &mut line.points {
pt.x += x;
pt.y += y;
}
}
self
}
}
fn main() {
let point = Point { x: 3., y: 2. };
let mut line = Line::new();
let mut rect = Rect::new();
line.add(point);
line.add(Point { x: 10., y: 15. });
println!("point = {:?}", point);
println!("line = {:?}", line);
rect.add(line);
rect.add_line().shift(100., 100.);
println!("rect = {:?}", rect);
let a = Rc::new(RefCell::new(vec![1, 2, 3]));
let b = Rc::clone(&a);
let c = Rc::clone(&a);
a.borrow_mut().push(4);
// *a.borrow_mut() += 10; //This doesn't work
println!("a = {:?}", a);
println!("b = {:?}", b);
println!("c = {:?}", c);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment