# Rust for JavaScript Developers - Pattern Matching and Enums
This is the fourth part in a series about introducing the Rust language to JavaScript developers. Here are all the chapters:
- Tooling Ecosystem Overview
- Variables and Data Types
- Functions and Control Flow
- Pattern Matching and Enums
# Pattern Matching
To understand Pattern Matching, let’s start with something familiar in JavaScript - Switch Case.
Here’s a simple example that uses switch case
in JavaScript:
1 | function print_color(color) { |
Here’s the equivalent Rust code:
1 | fn print_color(color: &str) { |
Most of the code should be immediately understandable. The match
expression has the following signature:
1 | match VALUE { |
The fat arrow =>
syntax might trip us up because of the similarities with JavaScript arrow functions but they’re unrelated. The last pattern that uses underscore _
is called the catchall pattern and is similar to the default case in switch case. Each PATTERN => EXPRESSION
combination is called a match arm
.
The above example doesn’t really convey how useful pattern matching is - it just looks like switch case with a different syntax and a fancy name. Let’s talk about destructuring and enums to understand why pattern matching is useful.
# Destructuring
Destructuring is the process of extracting the inner fields of an array or struct into separate variables. If you have used destructuring in JavaScript, it is very similar in Rust.
Here’s an example in JavaScript:
1 | let rgb = [96, 172, 57]; |
Here’s the same example in Rust:
1 | struct Person { |
# Comparing Structs
It’s very common to write “if this then that” type of code. Combining destructuring and pattern matching allows us to write these type of logic in a very concise way.
Let’s take this following example in JavaScript. It’s contrived but you have probably written something like this sometime in your career:
1 | const point = { x: 0, y: 30 }; |
Let’s write the same code in Rust using pattern matching:
1 | struct Point { |
It’s a bit concise compared to the if else
logic but also might be confusing as we’re performing comparison, destructuring and variable binding at the same time.
This is how it looks like visually:
We begin to see why it’s named as “pattern matching” - we take an input and see which pattern in the match arms “fits” better - It’s like the shape sorter toys that kids play with. Apart from comparison, we also do variable binding in the 2nd, 3rd and 4th match arms. We pass variables x or y or both to their respective expressions.
Pattern matching is also exhaustive
- that is, it forces you to handle all the possible cases. Try removing the last match arm and Rust won’t let you compile the code.
# Enum
JavaScript doesn’t have Enums but if you’ve used TypeScript, you can think of Rust’s Enums as a combination of TypeScript’s Enums and TypeScript’s Discriminated Unions
In the simplest case, Enums can be used as a group of constants.
For example, even though JavaScript doesn’t have Enums, you might have used this pattern:
1 | const DIRECTION = { |
Here, we could’ve defined the FORWARD, BACKWARD, LEFT and RIGHT as separate constants, yet grouping it inside the DIRECTION object has the following benefits:
- The names FORWARD, BACKWARD, LEFT and RIGHT are namespaced under DIRECTION so naming conflicts can be avoided
- It is self-documenting as we can quickly see all the valid directions available in the codebase
However, there are some problems with this approach:
- What if someone passes NORTH or UP as an argument to move_drone? To fix this, we can add a validation to make sure that only values present in the DIRECTION object is allowed in the move function.
- What if we decide to support UP and DOWN in future or rename LEFT/RIGHT to PORT/STARBOARD? We need to find all the places where similar switch-case or if-else is used. There’s a chance that we might miss out a few places which would cause issues in production.
Enums in strongly typed languages like Rust are more powerful as they solve these problems without us writing extra code.
- If a function can take in only a small set of valid inputs, Enums can be used to enforce this constraint
- Enums with pattern matching force you to cover all cases. Useful when you’re updating Enums in future
Here’s the equivalent Rust example:
1 | enum Direction { |
We access the variants
inside Enum using the ::
notation. Try editing this code by calling “move_drone(Direction::Up)” or adding “Down” as a new item in the Direction enum. In the first case, the compiler will throw an error saying that “Up” is not found in “Direction” and in the second case, the compiler will complain that we haven’t covered “Down” in the match block.
Rust Enums can do much more than act as a group of constants - we can also associate data with an Enum variant.
1 | enum Direction { |
Here, we’ve added one more Enum called Operation that contains “unit like” variants (PowerOn, PowerOff, Rotate) and “struct like” variants (Move, TakePhoto). Notice how we’ve used pattern matching with destructuring and variable binding.
If you’ve used TypeScript or Flow, this is similar to discriminated unions
or sum types
:
1 | interface PowerOn { |
# Option
We learnt about the Option
type in chapter 2. Option is actually an Enum with two variants - Some
and None
:
1 | enum Option<T> { |
This is how we handled the Option value in that chapter:
1 | fn read_file(path: &str) -> Option<&str> { |
Using pattern matching, we can refactor the logic as follows:
1 | fn main() { |