Rust: Pattern Matching

Rust 0.10

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.

For instance:

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s