Skip to content

Commit 8ca8c2a

Browse files
committed
Fix #1253: Document enum type aliases
1 parent dbcdccf commit 8ca8c2a

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/custom_types/enum.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,46 @@ fn main() {
5353
5454
```
5555

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+
5696
### See also:
5797

5898
[`match`][match], [`fn`][fn], and [`String`][str]

0 commit comments

Comments
 (0)