Skip to content

Commit b556f12

Browse files
committed
---
yaml --- r: 216990 b: refs/heads/stable c: f59f41e h: refs/heads/master v: v3
1 parent 77fdac7 commit b556f12

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

[refs]

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,5 @@ refs/heads/tmp: 378a370ff2057afeb1eae86eb6e78c476866a4a6
2929
refs/tags/1.0.0-alpha.2: 4c705f6bc559886632d3871b04f58aab093bfa2f
3030
refs/tags/homu-tmp: a5286998df566e736b32f6795bfc3803bdaf453d
3131
refs/tags/1.0.0-beta: 8cbb92b53468ee2b0c2d3eeb8567005953d40828
32-
refs/heads/stable: 8d50216e9dfb055d28abf9da35f91542c2e9fe90
32+
refs/heads/stable: f59f41e04c044f322285f80d17916bd207d8ed04
3333
refs/tags/1.0.0: 55bd4f8ff2b323f317ae89e254ce87162d52a375

branches/stable/src/doc/trpl/match.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,40 @@ let number = match x {
6161
```
6262

6363
Sometimes it’s a nice way of converting something from one type to another.
64+
65+
# Matching on enums
66+
67+
Another important use of the `match` keyword is to process the possible
68+
variants of an enum:
69+
70+
```rust
71+
enum Message {
72+
Quit,
73+
ChangeColor(i32, i32, i32),
74+
Move { x: i32, y: i32 },
75+
Write(String),
76+
}
77+
78+
fn quit() { /* ... */ }
79+
fn change_color(r: i32, g: i32, b: i32) { /* ... */ }
80+
fn move_cursor(x: i32, y: i32) { /* ... */ }
81+
82+
fn process_message(msg: Message) {
83+
match msg {
84+
Message::Quit => quit(),
85+
Message::ChangeColor(r, g, b) => change_color(r, g, b),
86+
Message::Move { x: x, y: y } => move_cursor(x, y),
87+
Message::Write(s) => println!("{}", s),
88+
};
89+
}
90+
```
91+
92+
Again, the Rust compiler checks exhaustiveness, so it demands that you
93+
have a match arm for every variant of the enum. If you leave one off, it
94+
will give you a compile-time error unless you use `_`.
95+
96+
Unlike the previous uses of `match`, you can’t use the normal `if`
97+
statement to do this. You can use the [`if let`][if-let] statement,
98+
which can be seen as an abbreviated form of `match`.
99+
100+
[if-let][if-let.html]

0 commit comments

Comments
 (0)