Skip to content

Instantly share code, notes, and snippets.

@bstrie
Last active August 29, 2015 14:08
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 bstrie/dfd6f61720cae708fefc to your computer and use it in GitHub Desktop.
Save bstrie/dfd6f61720cae708fefc to your computer and use it in GitHub Desktop.
trait HasArea {
fn area(&self) -> f64;
}
trait RectangularArea: HasArea {
fn area(&self) -> f64 {
self.length() * self.width()
}
fn length(&self) -> f64;
fn width(&self) -> f64;
}
struct Square {
dimension: f64
}
struct Rectangle {
length: f64,
width: f64
}
// These impls here are rejected by the compiler
// because we haven't implemented `HasArea` for these structs.
// However, `RectangularArea` inherits from `HasArea`
// and provides default implementations for all its methods.
// Can the compiler use this information to allow this program?
impl RectangularArea for Square {
fn length(&self) -> f64 { self.dimension }
fn width(&self) -> f64 { self.dimension }
}
impl RectangularArea for Rectangle {
fn length(&self) -> f64 { self.length }
fn width(&self) -> f64 { self.width }
}
fn print_area<T>(shape: T) where T: HasArea {
println!("{}", shape.area());
}
fn main() {
let s = Square { dimension: 2.0 };
let r = Rectangle { length: 3.0, width: 2.5 };
print_area(s);
print_area(r);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment