Skip to content

Commit 457aed7

Browse files
committed
trpl: move tuple-structs.md into structs.md
1 parent 2a5a320 commit 457aed7

File tree

3 files changed

+60
-61
lines changed

3 files changed

+60
-61
lines changed

src/doc/trpl/SUMMARY.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,6 @@
4343
* [Universal Function Call Syntax](ufcs.md)
4444
* [Crates and Modules](crates-and-modules.md)
4545
* [`const` and `static`](const-and-static.md)
46-
* [Tuple Structs](tuple-structs.md)
4746
* [Attributes](attributes.md)
4847
* [`type` aliases](type-aliases.md)
4948
* [Casting between types](casting-between-types.md)

src/doc/trpl/structs.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,3 +117,63 @@ ones, and it will copy the values you don’t specify:
117117
let origin = Point3d { x: 0, y: 0, z: 0 };
118118
let 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`.

src/doc/trpl/tuple-structs.md

Lines changed: 0 additions & 60 deletions
This file was deleted.

0 commit comments

Comments
 (0)