Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Important: traits are of unknown size, and so must be passed around
- // as a reference
- trait Shape {
- fn area(&self) -> f32;
- }
- // As seen here.
- struct ShapeCollection<'a> {
- shapes: Vec<&'a Shape>
- }
- // This function needs to return a ShapeCollection, but since the
- // data structure requires references to work, it seems impossible!
- fn make_shapes<'a>(needRectangle: bool, multiplier: f32) -> ShapeCollection<'a> {
- let rect = Rectangle {
- width: 42.0 * multiplier,
- height: 24.0 * multiplier
- };
- let circle = Circle {
- radius: 42.0 * multiplier
- };
- match needRectangle {
- true => ShapeCollection {
- shapes: vec![&rect, &circle]
- },
- false => ShapeCollection {
- shapes: vec![&circle]
- },
- }
- }
- // ^ This function won't compile because rect and circle do not
- // life long enough, and the compiler dies at this point
- // Impls if you're interested / want to compile, but not that important
- struct Rectangle {
- width: f32,
- height: f32
- }
- impl Shape for Rectangle {
- fn area(&self) -> f32 {
- self.width * self.height
- }
- }
- struct Circle {
- radius: f32
- }
- impl Shape for Circle {
- fn area(&self) -> f32 {
- (std::f32::consts::PI * self.radius).powf(2f32)
- }
- }
- enum Shape2 {
- Rectangle { width: f32, height: f32 },
- Circle { radius: f32 }
- }
- fn area(shape: Shape2) -> f32 {
- match shape {
- Shape2::Rectangle {width, height} => width * height,
- Shape2::Circle {radius} => (std::f32::consts::PI * radius).powf(2f32)
- }
- }
- struct Shape2Collection {
- shapes: Vec<Shape2>
- }
- fn make_shapes2(needRectangle: bool, multiplier: f32) -> Shape2Collection {
- let rect = Shape2::Rectangle {
- width: 42.0 * multiplier,
- height: 24.0 * multiplier
- };
- let circle = Shape2::Circle {
- radius: 42.0 * multiplier
- };
- match needRectangle {
- true => Shape2Collection {
- shapes: vec![rect, circle]
- },
- false => Shape2Collection {
- shapes: vec![circle]
- },
- }
- }
Add Comment
Please, Sign In to add comment