Enums and Pattern Matching in Rust
by Hexagon, 3 min read rust guide
Enums in Rust are far more powerful than in most languages. Combined with match, they let you describe exactly which states your data can be in, and make the compiler check that you've handled every one of them. This is also where we meet Option, Rust's answer to null.
Defining an Enum
An enum is a type that can be one of a fixed set of variants. Remember the traffic light from earlier in the series? Here it is as an enum:
Compare this with the version that took a &str. There's no _ case for
invalid colors anymore, because there are no invalid colors. A TrafficLight
can only be red, yellow or green, and calling the function with "purple"
doesn't compile.
Exhaustive Matching
Now, let's say we add a fourth state, a blinking yellow light used at night. Without changing the function:
The compiler points out every match in the program that needs updating. In a
large codebase, this is a huge help. In JavaScript, you'd have to search for
every place that checks the light, and hope you found them all.
Variants With Data
Each variant of an enum can carry its own data, of different types:
The match takes each variant apart, and gives names to the data inside. This
is called destructuring, and it's what makes enums so pleasant to work with.
Enums can have methods, just like structs.
Option: No More Null
Rust has no null and no undefined. When a value might be missing, you use
the enum Option, which is built into the language. It's defined like this:
The <T> means it works with any type. We'll get to that in the article about
generics. You've seen Option already, when find returned Some(3).
The important part is that an Option<i32> is not an i32. You can't use it as
a number until you've checked that there is one:
The billion-dollar mistake of null pointers, "Cannot read properties of undefined" in JavaScript, simply can't happen. The compiler makes you handle the missing case.
Handy Option methods
Writing a match for every Option gets long. There are methods for the
common cases:
|age| age + 1 is a closure, a small inline function. It's like
(age) => age + 1 in JavaScript. We'll look closer at closures in the article
about iterators.
if let and let else
When you only care about one pattern, match is more than you need. if let
runs a block if a value matches a pattern:
let else is the opposite. It takes a value out of a pattern, and if the value
doesn't match, the else block must leave the function:
This keeps the main path of a function free from nesting, and is one of my favorite features of the language.
More Patterns
Patterns can do more than pick an enum variant:
if x == y is called a match guard, an extra condition for that arm. The arms
are checked from top to bottom, and the first match wins.
There's also the matches! macro, for when you just need a bool:
Conclusion
Enums are one of the main reasons people enjoy writing Rust. Instead of juggling flags and strings, you describe the states your data can be in, and the compiler makes sure you handle them all.
Remember the student average that returned NaN when there were no scores?
With Option, the method can say that there is no average:
Option covers values that might be missing. For operations that might fail,
with a reason, Rust has a sibling called Result. That's next.