Skip to content

Commit

Permalink
Merge pull request #1270 from andymac-2/rectangle-ambiguity
Browse files Browse the repository at this point in the history
Rectangle ambiguity
  • Loading branch information
marioidival authored Sep 25, 2019
2 parents a0164b7 + 531c3c2 commit 1d6138a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 16 deletions.
25 changes: 15 additions & 10 deletions src/custom_types/structs.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,10 @@ struct Point {
// Structs can be reused as fields of another struct
#[allow(dead_code)]
struct Rectangle {
p1: Point,
p2: Point,
// A rectangle can be specified by where the top left and bottom right
// corners are in space.
top_left: Point,
bottom_right: Point,
}
fn main() {
Expand All @@ -44,23 +46,26 @@ fn main() {
// Instantiate a `Point`
let point: Point = Point { x: 0.3, y: 0.4 };
let point: Point = Point { x: 10.3, y: 0.4 };
// Access the fields of the point
println!("point coordinates: ({}, {})", point.x, point.y);
// Make a new point by using struct update syntax to use the fields of our other one
let new_point = Point { x: 0.1, ..point };
// `new_point.y` will be the same as `point.y` because we used that field from `point`
println!("second point: ({}, {})", new_point.x, new_point.y);
// Make a new point by using struct update syntax to use the fields of our
// other one
let bottom_right = Point { x: 5.2, ..point };
// `bottom_right.y` will be the same as `point.y` because we used that field
// from `point`
println!("second point: ({}, {})", bottom_right.x, bottom_right.y);
// Destructure the point using a `let` binding
let Point { x: my_x, y: my_y } = point;
let Point { x: top_edge, y: left_edge } = point;
let _rectangle = Rectangle {
// struct instantiation is an expression too
p1: Point { x: my_y, y: my_x },
p2: point,
top_left: Point { x: left_edge, y: top_edge },
bottom_right: bottom_right,
};
// Instantiate a unit struct
Expand Down
14 changes: 8 additions & 6 deletions src/std/box.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@ struct Point {
y: f64,
}
// A Rectangle can be specified by where its top left and bottom right
// corners are in space
#[allow(dead_code)]
struct Rectangle {
p1: Point,
p2: Point,
top_left: Point,
bottom_right: Point,
}
fn origin() -> Point {
Expand All @@ -38,14 +40,14 @@ fn main() {
// Stack allocated variables
let point: Point = origin();
let rectangle: Rectangle = Rectangle {
p1: origin(),
p2: Point { x: 3.0, y: 4.0 }
top_left: origin(),
bottom_right: Point { x: 3.0, y: -4.0 }
};
// Heap allocated rectangle
let boxed_rectangle: Box<Rectangle> = Box::new(Rectangle {
p1: origin(),
p2: origin()
top_left: origin(),
bottom_right: Point { x: 3.0, y: -4.0 },
});
// The output of functions can be boxed
Expand Down

0 comments on commit 1d6138a

Please sign in to comment.