1
1
% Tuple Structs
2
2
3
- Rust has another data type that's like a hybrid between a tuple and a struct,
4
- called a * tuple struct* . Tuple structs do have a name, but their fields don't:
3
+ Rust has another data type that's like a hybrid between a [ tuple] [ tuple ] and a
4
+ [ struct] [ struct ] , called a ‘tuple struct’. Tuple structs have a name, but
5
+ their fields don’t:
5
6
6
- ``` { rust}
7
+ ``` rust
7
8
struct Color (i32 , i32 , i32 );
8
9
struct Point (i32 , i32 , i32 );
9
10
```
10
11
12
+ [ tuple ] : primitive-types.html#tuples
13
+ [ struct ] : structs.html
14
+
11
15
These two will not be equal, even if they have the same values:
12
16
13
- ``` { rust}
17
+ ``` rust
14
18
# struct Color (i32 , i32 , i32 );
15
19
# struct Point (i32 , i32 , i32 );
16
20
let black = Color (0 , 0 , 0 );
@@ -20,7 +24,7 @@ let origin = Point(0, 0, 0);
20
24
It is almost always better to use a struct than a tuple struct. We would write
21
25
` Color ` and ` Point ` like this instead:
22
26
23
- ``` { rust}
27
+ ``` rust
24
28
struct Color {
25
29
red : i32 ,
26
30
blue : i32 ,
@@ -37,12 +41,12 @@ struct Point {
37
41
Now, we have actual names, rather than positions. Good names are important,
38
42
and with a struct, we have actual names.
39
43
40
- There _ is_ one case when a tuple struct is very useful, though, and that' s a
41
- tuple struct with only one element. We call this the * newtype* pattern, because
44
+ There _ is_ one case when a tuple struct is very useful, though, and that’ s a
45
+ tuple struct with only one element. We call this the ‘ newtype’ pattern, because
42
46
it allows you to create a new type, distinct from that of its contained value
43
47
and expressing its own semantic meaning:
44
48
45
- ``` { rust}
49
+ ``` rust
46
50
struct Inches (i32 );
47
51
48
52
let length = Inches (10 );
@@ -52,5 +56,5 @@ println!("length is {} inches", integer_length);
52
56
```
53
57
54
58
As you can see here, you can extract the inner integer type through a
55
- destructuring ` let ` , as we discussed previously in ' tuples.' In this case, the
59
+ destructuring ` let ` , as we discussed previously in ‘ tuples’. In this case, the
56
60
` let Inches(integer_length) ` assigns ` 10 ` to ` integer_length ` .
0 commit comments