@@ -61,3 +61,40 @@ let number = match x {
6161```
6262
6363Sometimes 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