Skip to content

Commit e294772

Browse files
committed
Add enum namespacing to the Guide.
Closes rust-lang#19556.
1 parent f7d18b9 commit e294772

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/doc/guide.md

+49
Original file line numberDiff line numberDiff line change
@@ -1160,6 +1160,55 @@ Where a `StringResult` is either an `StringOK`, with the result of a computation
11601160
`ErrorReason` with a `String` explaining what caused the computation to fail. These kinds of
11611161
`enum`s are actually very useful and are even part of the standard library.
11621162

1163+
Enum variants are namespaced under the enum names. For example, here is an example of using
1164+
our `StringResult`:
1165+
1166+
```rust
1167+
# enum StringResult {
1168+
# StringOK(String),
1169+
# ErrorReason(String),
1170+
# }
1171+
fn respond(greeting: &str) -> StringResult {
1172+
if greeting == "Hello" {
1173+
StringResult::StringOK("Good morning!".to_string())
1174+
} else {
1175+
StringResult::ErrorReason("I didn't understand you!".to_string())
1176+
}
1177+
}
1178+
```
1179+
1180+
Notice that we need both the enum name and the variant name: `StringResult::StringOK`, but
1181+
we didn't need to with `Ordering`, we just said `Greater` rather than `Ordering::Greater`.
1182+
There's a reason: the Rust prelude imports the variants of `Ordering` as well as the enum
1183+
itself. We can use the `use` keyword to do something similar with `StringResult`:
1184+
1185+
```rust
1186+
use StringResult::StringOK;
1187+
use StringResult::ErrorReason;
1188+
1189+
enum StringResult {
1190+
StringOK(String),
1191+
ErrorReason(String),
1192+
}
1193+
1194+
# fn main() {}
1195+
1196+
fn respond(greeting: &str) -> StringResult {
1197+
if greeting == "Hello" {
1198+
StringOK("Good morning!".to_string())
1199+
} else {
1200+
ErrorReason("I didn't understand you!".to_string())
1201+
}
1202+
}
1203+
```
1204+
1205+
We'll learn more about `use` later, but it's used to bring names into scope. `use` declarations
1206+
must come before anything else, which looks a little strange in this example, since we `use`
1207+
the variants before we define them. Anyway, in the body of `respond`, we can just say `StringOK`
1208+
now, rather than the full `StringResult::StringOK`. Importing variants can be convenient, but can
1209+
also cause name conflicts, so do this with caution. It's considered good style to rarely import
1210+
variants for this reason.
1211+
11631212
As you can see `enum`s with values are quite a powerful tool for data representation,
11641213
and can be even more useful when they're generic across types. But before we get to
11651214
generics, let's talk about how to use them with pattern matching, a tool that will

0 commit comments

Comments
 (0)