Match Statements

There exists another form of control flow in Rust's syntax, based on pattern matching: executing different blocks of code depending on a match for:

The main method of pattern matching in Rust is through a match statement, which takes a given variable and has defined sections of code that run if that variable's value satisfies a match for that section:

Depending on the type of the variable in question, ranges can be specified for matching patterns. The above example prints "Too small!" if the value is 1, 2, 3 or 4, and prints "Too big!" if the value is 6 or greater.


    

Note the matching clause marked with an underscore in the above example. This underscore acts as a wildcard: if the value of the variable matches none of the other patterns, the wildcard block of code will be executed.

As a side note, the macro being called in the wildcard clause is used to explicitly define areas of code that are manually known to be unreachable, hence its name. If the programmer is wrong, and the code explicitly defined as unreachable using this macro is indeed reached and executed during runtime, the macro will panic, with an error message that can be passed to it as a string.

It is forbidden to define a match statement with non-exhaustive patterns, that is, if not all possible values of a variable of a certain type are covered by the defined patterns:

Compiling temp v0.1.0
error[E0004]: non-exhaustive patterns: `i32::MIN..=0_i32` not covered
--> src/main.rs:3:9
|
3 | match num {
|   ^^^ pattern `i32::MIN..=0_i32` not covered
|
= note: the matched value is of type `i32`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
12~ },
13+ i32::MIN..=0_i32 => todo!()
|

For more information about this error, try `rustc --explain E0004`.
error: could not compile `temp` (bin "temp") due to 1 previous error

Exercise:
Complete the below match statement such that the hundred of variable num gets printed (e.g. 398 means that "300" is printed), assuming that num < 1000:


    

For matching on a variable with an enum type, either all possible discriminants must be included, or the wildcard must be included if this is not the case: