]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/custom_types/structs.md
New upstream version 1.50.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / custom_types / structs.md
1 # Structures
2
3 There are three types of structures ("structs") that can be created using the
4 `struct` keyword:
5
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.
9
10 ```rust,editable
11 #[derive(Debug)]
12 struct Person {
13 name: String,
14 age: u8,
15 }
16
17 // A unit struct
18 struct Unit;
19
20 // A tuple struct
21 struct Pair(i32, f32);
22
23 // A struct with two fields
24 struct Point {
25 x: f32,
26 y: f32,
27 }
28
29 // Structs can be reused as fields of another struct
30 #[allow(dead_code)]
31 struct Rectangle {
32 // A rectangle can be specified by where the top left and bottom right
33 // corners are in space.
34 top_left: Point,
35 bottom_right: Point,
36 }
37
38 fn main() {
39 // Create struct with field init shorthand
40 let name = String::from("Peter");
41 let age = 27;
42 let peter = Person { name, age };
43
44 // Print debug struct
45 println!("{:?}", peter);
46
47
48 // Instantiate a `Point`
49 let point: Point = Point { x: 10.3, y: 0.4 };
50
51 // Access the fields of the point
52 println!("point coordinates: ({}, {})", point.x, point.y);
53
54 // Make a new point by using struct update syntax to use the fields of our
55 // other one
56 let bottom_right = Point { x: 5.2, ..point };
57
58 // `bottom_right.y` will be the same as `point.y` because we used that field
59 // from `point`
60 println!("second point: ({}, {})", bottom_right.x, bottom_right.y);
61
62 // Destructure the point using a `let` binding
63 let Point { x: top_edge, y: left_edge } = point;
64
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,
69 };
70
71 // Instantiate a unit struct
72 let _unit = Unit;
73
74 // Instantiate a tuple struct
75 let pair = Pair(1, 0.1);
76
77 // Access the fields of a tuple struct
78 println!("pair contains {:?} and {:?}", pair.0, pair.1);
79
80 // Destructure a tuple struct
81 let Pair(integer, decimal) = pair;
82
83 println!("pair contains {:?} and {:?}", integer, decimal);
84 }
85 ```
86
87 ### Activity
88
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`.
94
95 ### See also
96
97 [`attributes`][attributes], and [destructuring][destructuring]
98
99 [attributes]: ../attribute.md
100 [c_struct]: https://en.wikipedia.org/wiki/Struct_(C_programming_language)
101 [destructuring]: ../flow_control/match/destructuring.md