@@ -117,3 +117,63 @@ ones, and it will copy the values you don’t specify:
117117let origin = Point3d { x : 0 , y : 0 , z : 0 };
118118let point = Point3d { z : 1 , x : 2 , .. origin };
119119```
120+
121+ # Tuple structs
122+
123+ Rust has another data type that’s like a hybrid between a [ tuple] [ tuple ] and a
124+ struct, called a ‘tuple struct’. Tuple structs have a name, but
125+ their fields don’t:
126+
127+ ``` rust
128+ struct Color (i32 , i32 , i32 );
129+ struct Point (i32 , i32 , i32 );
130+ ```
131+
132+ [ tuple ] : primitive-types.html#tuples
133+
134+ These two will not be equal, even if they have the same values:
135+
136+ ``` rust
137+ # struct Color (i32 , i32 , i32 );
138+ # struct Point (i32 , i32 , i32 );
139+ let black = Color (0 , 0 , 0 );
140+ let origin = Point (0 , 0 , 0 );
141+ ```
142+
143+ It is almost always better to use a struct than a tuple struct. We would write
144+ ` Color ` and ` Point ` like this instead:
145+
146+ ``` rust
147+ struct Color {
148+ red : i32 ,
149+ blue : i32 ,
150+ green : i32 ,
151+ }
152+
153+ struct Point {
154+ x : i32 ,
155+ y : i32 ,
156+ z : i32 ,
157+ }
158+ ```
159+
160+ Now, we have actual names, rather than positions. Good names are important,
161+ and with a struct, we have actual names.
162+
163+ There _ is_ one case when a tuple struct is very useful, though, and that’s a
164+ tuple struct with only one element. We call this the ‘newtype’ pattern, because
165+ it allows you to create a new type, distinct from that of its contained value
166+ and expressing its own semantic meaning:
167+
168+ ``` rust
169+ struct Inches (i32 );
170+
171+ let length = Inches (10 );
172+
173+ let Inches (integer_length ) = length ;
174+ println! (" length is {} inches" , integer_length );
175+ ```
176+
177+ As you can see here, you can extract the inner integer type through a
178+ destructuring ` let ` , just as with regular tuples. In this case, the
179+ ` let Inches(integer_length) ` assigns ` 10 ` to ` integer_length ` .
0 commit comments