Last active
August 29, 2015 14:08
-
-
Save bstrie/dfd6f61720cae708fefc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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