Skip to content

Instantly share code, notes, and snippets.

@hsk
Created July 4, 2014 10:05
Show Gist options
  • Save hsk/6984440313d64964b094 to your computer and use it in GitHub Desktop.
Save hsk/6984440313d64964b094 to your computer and use it in GitHub Desktop.
use std::f64::consts::PI;
trait Shape { fn new(area: f64) -> Self; }
struct Circle { radius: f64 }
struct Square { length: f64 }
impl Shape for Circle {
fn new(area: f64) -> Circle { Circle { radius: (area / PI).sqrt() } }
}
impl Shape for Square {
fn new(area: f64) -> Square { Square { length: area.sqrt() } }
}
fn draw_all(shapes: &[Box<Drawable>]) {
for shape in shapes.iter() { shape.draw(); }
}
trait Drawable { fn draw(&self); }
impl Drawable for Circle { fn draw(&self) { println!("Cirlce {}",self.radius) } }
impl Drawable for Square { fn draw(&self) { println!("Square {}",self.length) } }
fn main() {
let area = 42.5;
let c: Box<Circle> = box Shape::new(area);
let s: Box<Square> = box Shape::new(area);
draw_all([c,s]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment