Pattern Matching
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
:
Press + to interact
impl Person {fn greeting(&self) -> String {if self.job == Job::Teacher {format!("Hello, you're a teacher named {}", self.name)} else if self.job == Job::Scientist {format!("Hello, you're a scientist named {}", self.name)} else {format!("Huh, this shouldn't be possible...")}}}
There are two problems with this approach:
-
I had to add a bogus
else
clause 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), ...