Skip to content

Instantly share code, notes, and snippets.

@kenpratt
Created May 21, 2015 03:54
Show Gist options
  • Save kenpratt/60e05b0e9ec3e4f7a5f1 to your computer and use it in GitHub Desktop.
Save kenpratt/60e05b0e9ec3e4f7a5f1 to your computer and use it in GitHub Desktop.
Trying to use a trait as a field in an enum
trait Polygon {
fn area(&self) -> f32;
}
struct Circle {
radius: f32,
}
impl Polygon for Circle {
fn area(&self) -> f32 {
self.radius * std::f32::consts::PI * 2.0
}
}
struct Rectangle {
width: f32,
height: f32,
}
impl Polygon for Rectangle {
fn area(&self) -> f32 {
self.width * self.height
}
}
enum Thing {
Shape(Polygon),
Point,
}
fn exec(t: Thing) {
match t {
Thing::Shape(p) => println!("Polygon with area: {}", p.area()),
Thing::Point => println!("Point"),
}
}
fn main() {
exec(Thing::Shape(Circle{radius: 5.0}));
exec(Thing::Shape(Rectangle{width: 7.0, height: 14.0}));
exec(Thing::Point);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment