Skip to content

Commit

Permalink
Fix #1253: Document enum type aliases
Browse files Browse the repository at this point in the history
  • Loading branch information
adamchalmers committed Sep 13, 2019
1 parent dbcdccf commit 8ca8c2a
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/custom_types/enum.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,46 @@ fn main() {
```

## Type aliases

If you use a type alias, you can refer to each enum variant via its alias.
This might be useful if the enum's name is too long or too generic, and you
want to rename it.

```rust,editable
enum VeryVerboseEnumOfThingsToDoWithNumbers {
Add,
Subtract,
}
// Creates a type alias
type Operations = VeryVerboseEnumOfThingsToDoWithNumbers;
fn main() {
// We can refer to each variant via its alias, not its long and inconvenient
// name.
let x = Operations::Add;
}
```

The most common place you'll see this is in `impl` blocks using the `Self` alias.

```rust,editable
enum VeryVerboseEnumOfThingsToDoWithNumbers {
Add,
Subtract,
}
impl VeryVerboseEnumOfThingsToDoWithNumbers {
fn run(&self, x: i32, y: i32) -> i32 {
match self {
Self::Add => x + y,
Self::Subtract => x - y,
}
}
}
```

### See also:

[`match`][match], [`fn`][fn], and [`String`][str]
Expand Down

0 comments on commit 8ca8c2a

Please sign in to comment.