3 There are three types of structures ("structs") that can be created using the
6 * Tuple structs, which are, basically, named tuples.
7 * The classic [C structs][c_struct]
8 * Unit structs, which are field-less, are useful for generics.
21 struct Pair(i32, f32);
23 // A struct with two fields
29 // Structs can be reused as fields of another struct
32 // A rectangle can be specified by where the top left and bottom right
33 // corners are in space.
39 // Create struct with field init shorthand
40 let name = String::from("Peter");
42 let peter = Person { name, age };
45 println!("{:?}", peter);
48 // Instantiate a `Point`
49 let point: Point = Point { x: 10.3, y: 0.4 };
51 // Access the fields of the point
52 println!("point coordinates: ({}, {})", point.x, point.y);
54 // Make a new point by using struct update syntax to use the fields of our
56 let bottom_right = Point { x: 5.2, ..point };
58 // `bottom_right.y` will be the same as `point.y` because we used that field
60 println!("second point: ({}, {})", bottom_right.x, bottom_right.y);
62 // Destructure the point using a `let` binding
63 let Point { x: left_edge, y: top_edge } = point;
65 let _rectangle = Rectangle {
66 // struct instantiation is an expression too
67 top_left: Point { x: left_edge, y: top_edge },
68 bottom_right: bottom_right,
71 // Instantiate a unit struct
74 // Instantiate a tuple struct
75 let pair = Pair(1, 0.1);
77 // Access the fields of a tuple struct
78 println!("pair contains {:?} and {:?}", pair.0, pair.1);
80 // Destructure a tuple struct
81 let Pair(integer, decimal) = pair;
83 println!("pair contains {:?} and {:?}", integer, decimal);
89 1. Add a function `rect_area` which calculates the area of a `Rectangle` (try
90 using nested destructuring).
91 2. Add a function `square` which takes a `Point` and a `f32` as arguments, and
92 returns a `Rectangle` with its lower left corner on the point, and a width and
93 height corresponding to the `f32`.
97 [`attributes`][attributes], and [destructuring][destructuring]
99 [attributes]: ../attribute.md
100 [c_struct]: https://en.wikipedia.org/wiki/Struct_(C_programming_language)
101 [destructuring]: ../flow_control/match/destructuring.md