One of my favourite features of Rust is pattern matching. It’s a simple and elegant way to deal with not just structs, but also enums!
Here, we have an enum and a function to get the name out of this. In C, this would be very unsafe, as we cannot be guaranteed that our union has the right tag. But in Rust, the compiler nicely checks it all for us. It’s safe and expressive (just like many other features of Rust).
But that isn’t the only way to use pattern matching. While branching is one of its core features (in that sense, pattern matching is just like git), it doesn’t always have to be used. Another major advantage of pattern matching lies in the ability to exhaustively (not be be confused with exhausting, like writing down brilliant ideas like this) match over inputs.
Let’s look at the following example. Here, we have a struct representing a struct in a programming language. It has a name and fields. We then manually implement a custom hash trait for it because we are important and need a custom hash trait. We could have written a derive macro, but didn’t because we don’t understand how proc macros work.