Just a few steps need to be followed in order to learn more about pattern matching:
- 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.
- 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() }}
- However, pattern matching is way more powerful than that. For example, tuple elements can be extracted and selectively matched:
fn tuple_match(choices: ...