]> git.lizzy.rs Git - rust.git/blob - src/doc/book/structs.md
Unignore u128 test for stage 0,1
[rust.git] / src / doc / book / structs.md
1 % Structs
2
3 `struct`s are a way of creating more complex data types. For example, if we were
4 doing calculations involving coordinates in 2D space, we would need both an `x`
5 and a `y` value:
6
7 ```rust
8 let origin_x = 0;
9 let origin_y = 0;
10 ```
11
12 A `struct` lets us combine these two into a single, unified datatype with `x`
13 and `y` as field labels:
14
15 ```rust
16 struct Point {
17     x: i32,
18     y: i32,
19 }
20
21 fn main() {
22     let origin = Point { x: 0, y: 0 }; // origin: Point
23
24     println!("The origin is at ({}, {})", origin.x, origin.y);
25 }
26 ```
27
28 There’s a lot going on here, so let’s break it down. We declare a `struct` with
29 the `struct` keyword, and then with a name. By convention, `struct`s begin with
30 a capital letter and are camel cased: `PointInSpace`, not `Point_In_Space`.
31
32 We can create an instance of our `struct` via `let`, as usual, but we use a `key:
33 value` style syntax to set each field. The order doesn’t need to be the same as
34 in the original declaration.
35
36 Finally, because fields have names, we can access them through dot
37 notation: `origin.x`.
38
39 The values in `struct`s are immutable by default, like other bindings in Rust.
40 Use `mut` to make them mutable:
41
42 ```rust
43 struct Point {
44     x: i32,
45     y: i32,
46 }
47
48 fn main() {
49     let mut point = Point { x: 0, y: 0 };
50
51     point.x = 5;
52
53     println!("The point is at ({}, {})", point.x, point.y);
54 }
55 ```
56
57 This will print `The point is at (5, 0)`.
58
59 Rust does not support field mutability at the language level, so you cannot
60 write something like this:
61
62 ```rust,ignore
63 struct Point {
64     mut x: i32, // This causes an error.
65     y: i32,
66 }
67 ```
68
69 Mutability is a property of the binding, not of the structure itself. If you’re
70 used to field-level mutability, this may seem strange at first, but it
71 significantly simplifies things. It even lets you make things mutable on a temporary
72 basis:
73
74 ```rust,ignore
75 struct Point {
76     x: i32,
77     y: i32,
78 }
79
80 fn main() {
81     let mut point = Point { x: 0, y: 0 };
82
83     point.x = 5;
84
85     let point = point; // `point` is now immutable.
86
87     point.y = 6; // This causes an error.
88 }
89 ```
90
91 Your structure can still contain `&mut` pointers, which will let
92 you do some kinds of mutation:
93
94 ```rust
95 struct Point {
96     x: i32,
97     y: i32,
98 }
99
100 struct PointRef<'a> {
101     x: &'a mut i32,
102     y: &'a mut i32,
103 }
104
105 fn main() {
106     let mut point = Point { x: 0, y: 0 };
107
108     {
109         let r = PointRef { x: &mut point.x, y: &mut point.y };
110
111         *r.x = 5;
112         *r.y = 6;
113     }
114
115     assert_eq!(5, point.x);
116     assert_eq!(6, point.y);
117 }
118 ```
119
120 # Update syntax
121
122 A `struct` can include `..` to indicate that you want to use a copy of some
123 other `struct` for some of the values. For example:
124
125 ```rust
126 struct Point3d {
127     x: i32,
128     y: i32,
129     z: i32,
130 }
131
132 let mut point = Point3d { x: 0, y: 0, z: 0 };
133 point = Point3d { y: 1, .. point };
134 ```
135
136 This gives `point` a new `y`, but keeps the old `x` and `z` values. It doesn’t
137 have to be the same `struct` either, you can use this syntax when making new
138 ones, and it will copy the values you don’t specify:
139
140 ```rust
141 # struct Point3d {
142 #     x: i32,
143 #     y: i32,
144 #     z: i32,
145 # }
146 let origin = Point3d { x: 0, y: 0, z: 0 };
147 let point = Point3d { z: 1, x: 2, .. origin };
148 ```
149
150 # Tuple structs
151
152 Rust has another data type that’s like a hybrid between a [tuple][tuple] and a
153 `struct`, called a ‘tuple struct’. Tuple structs have a name, but their fields
154 don't. They are declared with the `struct` keyword, and then with a name
155 followed by a tuple:
156
157 [tuple]: primitive-types.html#tuples
158
159 ```rust
160 struct Color(i32, i32, i32);
161 struct Point(i32, i32, i32);
162
163 let black = Color(0, 0, 0);
164 let origin = Point(0, 0, 0);
165 ```
166
167 Here, `black` and `origin` are not the same type, even though they contain the
168 same values.
169
170 The members of a tuple struct may be accessed by dot notation or destructuring
171 `let`, just like regular tuples:
172
173 ```rust
174 # struct Color(i32, i32, i32);
175 # struct Point(i32, i32, i32);
176 # let black = Color(0, 0, 0);
177 # let origin = Point(0, 0, 0);
178 let black_r = black.0;
179 let Point(_, origin_y, origin_z) = origin;
180 ```
181
182 Patterns like `Point(_, origin_y, origin_z)` are also used in
183 [match expressions][match].
184
185 One case when a tuple struct is very useful is when it has only one element.
186 We call this the ‘newtype’ pattern, because it allows you to create a new type
187 that is distinct from its contained value and also expresses its own semantic
188 meaning:
189
190 ```rust
191 struct Inches(i32);
192
193 let length = Inches(10);
194
195 let Inches(integer_length) = length;
196 println!("length is {} inches", integer_length);
197 ```
198
199 As above, you can extract the inner integer type through a destructuring `let`.
200 In this case, the `let Inches(integer_length)` assigns `10` to `integer_length`.
201 We could have used dot notation to do the same thing:
202
203 ```rust
204 # struct Inches(i32);
205 # let length = Inches(10);
206 let integer_length = length.0;
207 ```
208
209 It's always possible to use a `struct` instead of a tuple struct, and can be
210 clearer. We could write `Color` and `Point` like this instead:
211
212 ```rust
213 struct Color {
214     red: i32,
215     blue: i32,
216     green: i32,
217 }
218
219 struct Point {
220     x: i32,
221     y: i32,
222     z: i32,
223 }
224 ```
225
226 Good names are important, and while values in a tuple struct can be
227 referenced with dot notation as well, a `struct` gives us actual names,
228 rather than positions.
229
230 [match]: match.html
231
232 # Unit-like structs
233
234 You can define a `struct` with no members at all:
235
236 ```rust
237 struct Electron {} // Use empty braces...
238 struct Proton;     // ...or just a semicolon.
239
240 // Whether you declared the struct with braces or not, do the same when creating one.
241 let x = Electron {};
242 let y = Proton;
243 ```
244
245 Such a `struct` is called ‘unit-like’ because it resembles the empty
246 tuple, `()`, sometimes called ‘unit’. Like a tuple struct, it defines a
247 new type.
248
249 This is rarely useful on its own (although sometimes it can serve as a
250 marker type), but in combination with other features, it can become
251 useful. For instance, a library may ask you to create a structure that
252 implements a certain [trait][trait] to handle events. If you don’t have
253 any data you need to store in the structure, you can create a
254 unit-like `struct`.
255
256 [trait]: traits.html