Pattern Matching
Explore how to implement pattern matching in Rust using enums to handle different cases cleanly and safely. Understand how the match expression works with enum variants, ensuring your code handles all possibilities with compiler support and avoiding unnecessary clauses. Gain skills to improve code clarity and type safety in Rust applications.
We'll cover the following...
Let’s write a function to produce a greeting for someone based on their job. Here’s one naive approach using if/else:
There are two problems with this approach:
-
I had to add a bogus
elseclause at the end to handle the possibility that the person is neither a teacher nor a scientist. However, we know that can never happen! Nonetheless, if I leave that off, the compiler complains. That’s annoying. -
If in the future you decide to add a new job (maybe a plumber), ...