Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3.1 Structures - incorrectly assigns coordinates to Points in Rectangle #1883

Closed
cyrts opened this issue Sep 7, 2024 · 1 comment
Closed

Comments

@cyrts
Copy link
Contributor

cyrts commented Sep 7, 2024

Hello, I'm currently going through "Rust by Example" and I'm very grateful for it, thank you. I was doing the activity which says to create a rect_area function to calculate the area of a Rectangle. When I completed this I noticed that I was getting a negative result when using my function on the already-created Rectangle in the default code. I found out that this is because the _rectangle.top_left.x coordinate is actually further right than the _rectangle.bottom_right.x coordinate, which is wrong-- bottom_right should have the right-most x value.

// Instantiate a `Point`
let point: Point = Point { x: 10.3, y: 0.4 };
let another_point: Point = Point { x: 5.2, y: 0.2 };

// Make a new point by using struct update syntax to use the fields of our
// other one
let bottom_right = Point { x: 5.2, ..another_point };

// Destructure the point using a `let` binding
let Point { x: left_edge, y: top_edge } = point;

let _rectangle = Rectangle {
   // struct instantiation is an expression too
  top_left: Point { x: left_edge, y: top_edge },
  bottom_right: bottom_right,
};

I've removed irrelevant code, but notice how the bottom_right of _rectangle is actually on the bottom left, and the top_left is actually on the top right!

Finding the area of a rectangle with these coordinates (if one goes by the names of the fields) would be (x2-x1)* (y2-y1) would yield a negative result! This can all be fixed by swapping the initial x values given on lines 50 and 51, and then also correcting the x value given on line 58.

It should be like this:

// Instantiate a `Point`
    let point: Point = Point { x: 5.2, y: 0.4 };
    let another_point: Point = Point { x: 10.3, y: 0.2 };
//...
//...
//...
    let bottom_right = Point { x: 10.3, ..another_point };

Thank you for your attention to this matter.

@cyrts
Copy link
Contributor Author

cyrts commented Sep 7, 2024

I have made these corrections and issued a PR for these changes here: #1884

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants