Skip to content

Commit b854723

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

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/custom_types/enum.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,43 @@ 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+
60+
```rust,editable
61+
enum VeryVerboseEnumOfThingsToDoWithNumbers {
62+
Add,
63+
Subtract,
64+
}
65+
66+
// Creates a type alias
67+
type Operations = VeryVerboseEnumOfThingsToDoWithNumbers;
68+
69+
fn main() {
70+
// We can refer to each variant via its alias, not its long and inconvenient name.
71+
let x = Operations::Add;
72+
}
73+
```
74+
75+
The most common place you'll see this is in `impl` blocks using the `Self` alias.
76+
77+
```rust,editable
78+
enum VeryVerboseEnumOfThingsToDoWithNumbers {
79+
Add,
80+
Subtract,
81+
}
82+
83+
impl VeryVerboseEnumOfThingsToDoWithNumbers {
84+
fn run(&self, x: i32, y: i32) -> i32 {
85+
match self {
86+
Self::Add => x + y,
87+
Self::Subtract => x - y,
88+
}
89+
}
90+
}
91+
```
92+
5693
### See also:
5794

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

0 commit comments

Comments
 (0)