From 8ca8c2a2f9e238d40c87527d4896e81a89e28427 Mon Sep 17 00:00:00 2001 From: Adam Chalmers Date: Fri, 13 Sep 2019 09:19:58 -0500 Subject: [PATCH] Fix #1253: Document enum type aliases --- src/custom_types/enum.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/custom_types/enum.md b/src/custom_types/enum.md index 5eae819adc..59c27d5904 100644 --- a/src/custom_types/enum.md +++ b/src/custom_types/enum.md @@ -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]