Skip to content

Instantly share code, notes, and snippets.

@brson
Created October 13, 2012 20:56
Show Gist options
  • Save brson/3886118 to your computer and use it in GitHub Desktop.
Save brson/3886118 to your computer and use it in GitHub Desktop.
trait Positioned {
fn get_x(&self) -> int;
fn get_y(&self) -> int;
fn set_x(&self, x: int);
fn set_y(&self, y: int);
}
trait Movable: Positioned {
fn translate(&self, dx: int, dy: int) {
self.set_x(self.get_x() + dx);
self.set_y(self.get_y() + dy);
}
}
trait Renderable: Positioned {
fn render(&self) {
io::println(fmt!("%?, %?", self.get_x(), self.get_y());
}
}
struct Point {
mut x: int,
mut y: int
}
struct Entity {
mut pos: Point,
}
impl Point: Positioned { ... }
impl Entity: Moveable;
impl Entity: Renderable;
impl Entity: Positioned {
// How to get rid of this boilerplate? Not sure yet
// The compiler can probably auto-derive it eventually.
fn get_x(&self) -> int { self.pos.get_x() }
...
}
fn main() {
let mut e: Entity = Entity {
pos: Point{x: 0, y: 0},
};
e.translate(5, 10);
e.render();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment