Rust Enums and Pattern Matching: Type-Safe Alternatives
Rust enums define a type that can be one of several variants, each holding its own data. They're used to model states like Loading/Success/Error or handle optional values with Option<T>.
Why it exists
Enums exist to eliminate bugs that arise from data without context, like using special values such as null, -1, or empty strings to represent a state. By encoding all possible states of a value into the type system itself, Rust makes invalid states unrepresentable, and the compiler can verify correctness.
The mental model
Think of a Rust enum as a box that can hold one of several pre-defined items, and the box is always labeled with what's inside. You might have a Message box that can hold either a Quit instruction, a Move instruction with coordinates, or a Write instruction with a string. You can't accidentally treat the Quit instruction as if it has a string, because the type system won't let you. The match keyword is how you safely check the label and handle the contents accordingly.
How it works
An enum is defined with variants. A variant can be a simple unit (e.g., IpAddrKind::V4) or can contain data (e.g., IpAddrKind::V6(String)). To use an enum's value, you use a match expression. This expression is forced by the compiler to be exhaustive, meaning you must provide a code path, or "arm", for every possible variant. This prevents you from forgetting to handle a case. For situations where you only care about one variant and want to ignore the rest, the if let construct provides a more concise syntax.
When to use it
Use enums whenever a value can be one of a fixed set of possibilities, especially if those possibilities carry different data. This is fundamental for modeling state machines, representing events, defining custom error types, and handling optionality. The standard library's Option<T> and Result<T, E> are the most common and powerful examples.
When not to use it
Avoid enums when the set of variants is not known at compile time or needs to be extended dynamically. If you need to add new types at runtime without recompiling, a trait object (dynamic dispatch) is a more appropriate tool. Enums are for closed, compile-time known sets of variations.
One canonical example
The Option<T> enum, defined as enum Option<T> { Some(T), None }, is the canonical use case. It provides a type-safe way to handle values that might be absent, solving the "billion-dollar mistake" of null pointers. The compiler forces you to handle both the Some(value) and None cases, ensuring you can't use a value that isn't there.
Interview question
Which of the following best describes the primary safety benefit of Rust's enums and pattern matching?
- a.They ensure that all possible states of a value are explicitly handled, preventing unrepresentable or forgotten cases.Correct
- b.They automatically convert any unexpected or invalid data into a safe, default enum variant.
- c.They enable a single enum type to simultaneously store multiple different data types within its variants.
- d.They allow for the dynamic addition of new data variants at runtime without requiring code changes.
Why? this is the answer
The card states that enums make "invalid states unrepresentable" and that `match` expressions are "exhaustive," forcing handling of all variants. This prevents forgotten cases. Option D describes a scenario where enums should not be used, as they are for compile-time known sets of variations.
Just read this? Test yourself on what you have been reading.
Read the original → doc.rust-lang.org
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on rust — each one lists the topics its interview covers.
See open roles