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`
12 A `struct` lets us combine these two into a single, unified datatype with `x`
13 and `y` as field labels:
22 let origin = Point { x: 0, y: 0 }; // origin: Point
24 println!("The origin is at ({}, {})", origin.x, origin.y);
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`.
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.
36 Finally, because fields have names, we can access them through dot
39 The values in `struct`s are immutable by default, like other bindings in Rust.
40 Use `mut` to make them mutable:
49 let mut point = Point { x: 0, y: 0 };
53 println!("The point is at ({}, {})", point.x, point.y);
57 This will print `The point is at (5, 0)`.
59 Rust does not support field mutability at the language level, so you cannot
60 write something like this:
64 mut x: i32, // This causes an error.
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
81 let mut point = Point { x: 0, y: 0 };
85 let point = point; // `point` is now immutable.
87 point.y = 6; // This causes an error.
91 Your structure can still contain `&mut` pointers, which will let
92 you do some kinds of mutation:
100 struct PointRef<'a> {
106 let mut point = Point { x: 0, y: 0 };
109 let r = PointRef { x: &mut point.x, y: &mut point.y };
115 assert_eq!(5, point.x);
116 assert_eq!(6, point.y);
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
125 #![feature(field_init_shorthand)]
134 // Create struct with field init shorthand
137 let peter = Person { name, age };
139 // Print debug struct
140 println!("{:?}", peter);
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:
156 let mut point = Point3d { x: 0, y: 0, z: 0 };
157 point = Point3d { y: 1, .. point };
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:
170 let origin = Point3d { x: 0, y: 0, z: 0 };
171 let point = Point3d { z: 1, x: 2, .. origin };
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
181 [tuple]: primitive-types.html#tuples
184 struct Color(i32, i32, i32);
185 struct Point(i32, i32, i32);
187 let black = Color(0, 0, 0);
188 let origin = Point(0, 0, 0);
191 Here, `black` and `origin` are not the same type, even though they contain the
194 The members of a tuple struct may be accessed by dot notation or destructuring
195 `let`, just like regular tuples:
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;
206 Patterns like `Point(_, origin_y, origin_z)` are also used in
207 [match expressions][match].
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
217 let length = Inches(10);
219 let Inches(integer_length) = length;
220 println!("length is {} inches", integer_length);
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:
228 # struct Inches(i32);
229 # let length = Inches(10);
230 let integer_length = length.0;
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:
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.
258 You can define a `struct` with no members at all:
261 struct Electron {} // Use empty braces...
262 struct Proton; // ...or just a semicolon.
264 // Whether you declared the struct with braces or not, do the same when creating one.
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
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