]> git.lizzy.rs Git - rust.git/blob - src/doc/book/structs.md
Rollup merge of #39604 - est31:i128_tests, r=alexcrichton
[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 Initialization of a data structure (struct, enum, union) can be simplified if
121 fields of the data structure are initialized with variables which has same
122 names as the fields.
123
124 ```
125 #![feature(field_init_shorthand)]
126
127 #[derive(Debug)]
128 struct Person<'a> {
129     name: &'a str,
130     age: u8
131 }
132
133 fn main() {
134     // Create struct with field init shorthand
135     let name = "Peter";
136     let age = 27;
137     let peter = Person { name, age };
138
139     // Print debug struct
140     println!("{:?}", peter);
141 }
142 ```
143
144 # Update syntax
145
146 A `struct` can include `..` to indicate that you want to use a copy of some
147 other `struct` for some of the values. For example:
148
149 ```rust
150 struct Point3d {
151     x: i32,
152     y: i32,
153     z: i32,
154 }
155
156 let mut point = Point3d { x: 0, y: 0, z: 0 };
157 point = Point3d { y: 1, .. point };
158 ```
159
160 This gives `point` a new `y`, but keeps the old `x` and `z` values. It doesn’t
161 have to be the same `struct` either, you can use this syntax when making new
162 ones, and it will copy the values you don’t specify:
163
164 ```rust
165 # struct Point3d {
166 #     x: i32,
167 #     y: i32,
168 #     z: i32,
169 # }
170 let origin = Point3d { x: 0, y: 0, z: 0 };
171 let point = Point3d { z: 1, x: 2, .. origin };
172 ```
173
174 # Tuple structs
175
176 Rust has another data type that’s like a hybrid between a [tuple][tuple] and a
177 `struct`, called a ‘tuple struct’. Tuple structs have a name, but their fields
178 don't. They are declared with the `struct` keyword, and then with a name
179 followed by a tuple:
180
181 [tuple]: primitive-types.html#tuples
182
183 ```rust
184 struct Color(i32, i32, i32);
185 struct Point(i32, i32, i32);
186
187 let black = Color(0, 0, 0);
188 let origin = Point(0, 0, 0);
189 ```
190
191 Here, `black` and `origin` are not the same type, even though they contain the
192 same values.
193
194 The members of a tuple struct may be accessed by dot notation or destructuring
195 `let`, just like regular tuples:
196
197 ```rust
198 # struct Color(i32, i32, i32);
199 # struct Point(i32, i32, i32);
200 # let black = Color(0, 0, 0);
201 # let origin = Point(0, 0, 0);
202 let black_r = black.0;
203 let Point(_, origin_y, origin_z) = origin;
204 ```
205
206 Patterns like `Point(_, origin_y, origin_z)` are also used in
207 [match expressions][match].
208
209 One case when a tuple struct is very useful is when it has only one element.
210 We call this the ‘newtype’ pattern, because it allows you to create a new type
211 that is distinct from its contained value and also expresses its own semantic
212 meaning:
213
214 ```rust
215 struct Inches(i32);
216
217 let length = Inches(10);
218
219 let Inches(integer_length) = length;
220 println!("length is {} inches", integer_length);
221 ```
222
223 As above, you can extract the inner integer type through a destructuring `let`.
224 In this case, the `let Inches(integer_length)` assigns `10` to `integer_length`.
225 We could have used dot notation to do the same thing:
226
227 ```rust
228 # struct Inches(i32);
229 # let length = Inches(10);
230 let integer_length = length.0;
231 ```
232
233 It's always possible to use a `struct` instead of a tuple struct, and can be
234 clearer. We could write `Color` and `Point` like this instead:
235
236 ```rust
237 struct Color {
238     red: i32,
239     blue: i32,
240     green: i32,
241 }
242
243 struct Point {
244     x: i32,
245     y: i32,
246     z: i32,
247 }
248 ```
249
250 Good names are important, and while values in a tuple struct can be
251 referenced with dot notation as well, a `struct` gives us actual names,
252 rather than positions.
253
254 [match]: match.html
255
256 # Unit-like structs
257
258 You can define a `struct` with no members at all:
259
260 ```rust
261 struct Electron {} // Use empty braces...
262 struct Proton;     // ...or just a semicolon.
263
264 // Whether you declared the struct with braces or not, do the same when creating one.
265 let x = Electron {};
266 let y = Proton;
267 ```
268
269 Such a `struct` is called ‘unit-like’ because it resembles the empty
270 tuple, `()`, sometimes called ‘unit’. Like a tuple struct, it defines a
271 new type.
272
273 This is rarely useful on its own (although sometimes it can serve as a
274 marker type), but in combination with other features, it can become
275 useful. For instance, a library may ask you to create a structure that
276 implements a certain [trait][trait] to handle events. If you don’t have
277 any data you need to store in the structure, you can create a
278 unit-like `struct`.
279
280 [trait]: traits.html