Skip to content

Instantly share code, notes, and snippets.

@farnoy
Created March 3, 2013 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save farnoy/5075979 to your computer and use it in GitHub Desktop.
Save farnoy/5075979 to your computer and use it in GitHub Desktop.
rust polymorphism
extern mod std;
enum Drawable {
Rectangle(uint, uint, bool),
Triangle(uint, bool)
}
fn draw_triangle(height: uint, empty: bool) {
let mut n = 1;
info!("Drawing %s triangle", (match empty {true => "empty", false => "full"}));
while n <= height {
let mut m = 1;
while m <= n {
if !empty || n == 1 || n == height || m == 1 || m == n {
io::print("*");
} else {
io::print(" ")
}
m += 1;
}
io::println("");
n += 1;
}
}
fn draw_rectangle(width: uint, height: uint, empty: bool) {
let mut n = 1;
info!("Drawing %s rectangle", (match empty {true => "empty", false => "full"}));
while n <= height {
let mut m = 1;
while m <= width {
if !empty || n == 1 || n == height || m == 1 || m == width {
io::print("*");
} else {
io::print(" ");
}
m += 1;
}
io::println("");
n += 1;
}
}
impl Drawable {
fn draw(&self) {
match *self {
Triangle(height, empty) => draw_triangle(height, empty),
Rectangle(width, height, empty) => draw_rectangle(width, height, empty)
}
}
}
fn main() {
let drawables : ~[@Drawable] = ~[@Triangle(5, false), @Rectangle(8, 4, true), @Triangle(8, true)];
for drawables.each |drawable| {
drawable.draw();
io::println("");
}
}
$ rustc hello.rs && RUST_LOG=hello ./hello
rust: ~"Drawing full triangle"
*
**
***
****
*****
rust: ~"Drawing empty rectangle"
********
* *
* *
********
rust: ~"Drawing empty triangle"
*
**
* *
* *
* *
* *
* *
********
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment