@@ -53,11 +53,56 @@ fn main() {
53
53
54
54
```
55
55
56
+ ## Type aliases
57
+
58
+ If you use a type alias, you can refer to each enum variant via its alias.
59
+ This might be useful if the enum's name is too long or too generic, and you
60
+ want to rename it.
61
+
62
+ ``` rust,editable
63
+ enum VeryVerboseEnumOfThingsToDoWithNumbers {
64
+ Add,
65
+ Subtract,
66
+ }
67
+
68
+ // Creates a type alias
69
+ type Operations = VeryVerboseEnumOfThingsToDoWithNumbers;
70
+
71
+ fn main() {
72
+ // We can refer to each variant via its alias, not its long and inconvenient
73
+ // name.
74
+ let x = Operations::Add;
75
+ }
76
+ ```
77
+
78
+ The most common place you'll see this is in ` impl ` blocks using the ` Self ` alias.
79
+
80
+ ``` rust,editable
81
+ enum VeryVerboseEnumOfThingsToDoWithNumbers {
82
+ Add,
83
+ Subtract,
84
+ }
85
+
86
+ impl VeryVerboseEnumOfThingsToDoWithNumbers {
87
+ fn run(&self, x: i32, y: i32) -> i32 {
88
+ match self {
89
+ Self::Add => x + y,
90
+ Self::Subtract => x - y,
91
+ }
92
+ }
93
+ }
94
+ ```
95
+
96
+ To learn more about enums and type aliases, you can read the
97
+ [ stabilization report] [ aliasreport ] from when this feature was stabilized into
98
+ Rust.
99
+
56
100
### See also:
57
101
58
- [ ` match ` ] [ match ] , [ ` fn ` ] [ fn ] , and [ ` String ` ] [ str ]
102
+ [ ` match ` ] [ match ] , [ ` fn ` ] [ fn ] , and [ ` String ` ] [ str ] , [ ]
59
103
60
104
[ c_struct ] : https://en.wikipedia.org/wiki/Struct_(C_programming_language)
61
105
[ match ] : ../flow_control/match.md
62
106
[ fn ] : ../fn.md
63
107
[ str ] : ../std/str.md
108
+ [ aliasreport ] : https://github.com/rust-lang/rust/pull/61682/#issuecomment-502472847
0 commit comments