How to do it...

Just a few steps need to be followed in order to learn more about pattern matching:

  1. Create a new binary project using cargo new pattern-matching. This time, we'll run an actual executable! Again, open the project using Visual Studio Code or another editor.
  2. Let's check out literal matching. Just like a switch-case statement in other languages, each matching arm can match to literals as well:
fn literal_match(choice: usize) -> String {    match choice {        0 | 1 => "zero or one".to_owned(),        2 ... 9 => "two to nine".to_owned(),        10 => "ten".to_owned(),        _ => "anything else".to_owned()    }}
  1. However, pattern matching is way more powerful than that. For example, tuple elements can be extracted and selectively matched:
fn tuple_match(choices: ...

Get Rust Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.