11% Structs
22
3- A struct is another form of a * record type* , just like a tuple. There's a
4- difference: structs give each element that they contain a name, called a
5- * field* or a * member* . Check it out:
3+ Structs are a way of creating more complex datatypes. 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:
613
714``` rust
815struct Point {
@@ -17,7 +24,7 @@ fn main() {
1724}
1825```
1926
20- There' s a lot going on here, so let' s break it down. We declare a struct with
27+ There’ s a lot going on here, so let’ s break it down. We declare a struct with
2128the ` struct ` keyword, and then with a name. By convention, structs begin with a
2229capital letter and are also camel cased: ` PointInSpace ` , not ` Point_In_Space ` .
2330
@@ -31,7 +38,7 @@ notation: `origin.x`.
3138The values in structs are immutable by default, like other bindings in Rust.
3239Use ` mut ` to make them mutable:
3340
34- ``` { rust}
41+ ``` rust
3542struct Point {
3643 x : i32 ,
3744 y : i32 ,
@@ -47,3 +54,36 @@ fn main() {
4754```
4855
4956This will print ` The point is at (5, 0) ` .
57+
58+ Rust does not support mutability at the field level, so you cannot write
59+ something like this:
60+
61+ ``` rust,ignore
62+ struct Point {
63+ mut x: i32,
64+ y: i32,
65+ }
66+ ```
67+
68+ Mutability is a property of the binding, not of the structure itself. If you’re
69+ used to field-level mutability, this may seem strange at first, but it
70+ significantly simplifies things. It even lets you make things mutable for a short
71+ time only:
72+
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; // this new binding is immutable
86+
87+ point.y = 6; // this causes an error, because `point` is immutable!
88+ }
89+ ```
0 commit comments