Skip to content

Activity seems misleading on Custom Types -Structures #1194

Closed
@matthewharwood

Description

@matthewharwood

Activity
Add a function rect_area which calculates the area of a rectangle (try using nested destructuring).

https://github.com/rust-lang/rust-by-example/blob/master/src/custom_types/structs.md

Given the example, I'm not too sure how we should be calculating the area or the rectangle.

I've made an abridged version of the question/answer:

use std::fmt::{self, Formatter, Display};

struct Point {
    x: f32,
    y: f32,
}

struct Rectangle {
    p1: Point,
    p2: Point,
}

impl Display for Point {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "x: {}, y:{}", self.x, self.y)
    }
    
}
impl Display for Rectangle {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "(p1: {}, p2: {})", self.p1, self.p2)
    }
    
}

 fn rect_area(rect: Rectangle) -> f32 {
    // Is this what you were looking for? seems misleading if so
    // (rect.p1.x - rect.p2.x)*(rect.p1.y - rect.p2.y)
 }
fn main() {
    let point: Point = Point { x: 0.3, y: 0.4 };
    let Point { x: my_x, y: my_y } = point;

    let _rectangle = Rectangle {
        p1: Point { x: my_y, y: my_x },
        p2: point,
    };

    println!("{}", _rectangle);
   //println!("{}", rect_area(_rectangle));
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions