Skip to content

Instantly share code, notes, and snippets.

/shapes.rs Secret

Created March 18, 2014 10:06
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 anonymous/fe87c51acc652fa049eb to your computer and use it in GitHub Desktop.
Save anonymous/fe87c51acc652fa049eb to your computer and use it in GitHub Desktop.
// you can't subclass, I'll use an example where each object has its own position instead
// be careful: this code sucks, compile with "rustc shapes.rs"
// a Point will be a "tuple struct" because I like the idea
struct Point(int, int); // xpos and ypos in your C++
// Points are "ToStr"ingable but not Drawable in my program
impl ToStr for Point {
fn to_str(&self) -> ~str {
// you must use match to extract values from tuples or something
// refs are scary in Rust so read the tutorial, I don't know what I am doing
match *self {
Point(x, y) => format!("Point({}, {})", x, y)
}
}
}
// the Drawable trait that each shape will have to implement
trait Drawable {
fn draw(&self) -> bool;
}
// a Rectangle with uint instead of size_t, but you can specify u16, u32, u64... instead
// also it has a Point for its position because it's fun
struct Rectangle {
position: Point,
width: uint,
height: uint
}
impl Rectangle {
// there are no constructors in Rust, but they are almost always named new or new_something. They have considered adding a Drop trait for destructors though
fn new(x: int, y: int, w: uint, h: uint) -> Rectangle {
Rectangle { position: Point(x, y), width: w, height: h }
}
// only one name for each method...
fn new_with_size(w: uint, h: uint) -> Rectangle {
Rectangle { position: Point(0, 0), width: w, height: h }
}
// be careful, I don't understand all the pointers and refs of Rust, maybe you could change "p" to be a &Point or something
fn new_with_point(p: Point) -> Rectangle {
Rectangle { position: p, width: 0, height: 0 }
}
}
// a Rectangle can be drawn now, wonderful!
impl Drawable for Rectangle {
fn draw(&self) -> bool {
// you shouldn't need to write position.to_str(), there has to be a module like fmt to do that automatically from the compiler
println(format!("I am a rectangle at {} with size ({}, {})", self.position.to_str(), self.width, self.height));
return true;
}
}
fn main() {
let r: Rectangle = Rectangle::new(10, 10, 640, 480);
r.draw();
}
// that's all folks!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment