One of Rust’s feature is pattern matching. Pattern matching is also available in languages such as Prolog, Erlang and Haskell.
In Rust you do pattern matching with the match expression. You can use pattern matching as a basic switch statement:
Here the underscore can be interpreted to mean anything. Since there is no fall through between the cases and the last one will match any values which haven’t been matched yet, it will act like a default case.
match let’s us do so much more than in many traditional C based languages.
This example introduces variables and conditionals as well as ranges.
With variables and conditionals you can also start writing recursive matching functions. These might seem odd if you aren’t used to such constructs, but once you do you’ll find them very expressive and powerful.
Here are two simple examples, defining a factorial function and a Fibonacci function:
Pattern matching also allows us to do destructuring, which I will talk about in a later post.