Enums and Pattern Matching
Enums that carry data, `Option`, `match` and exhaustiveness, `if let` and `let else`, and the pattern syntax.
11 questions
JuniorTheoryCommonHow do Rust enums differ from C and Java enums, and when do they beat a struct?
How do Rust enums differ from C and Java enums, and when do they beat a struct?
A C enum is named integers and a Java enum a fixed set of objects with the same fields; a Rust variant carries its own data, and a value is exactly one variant, read via match or if let. Pick an enum when a field fits only some states.
Common mistakes
- ✗Treating a Rust
enumas a list of named integer constants, as in C - ✗Expecting to read a variant's data without first checking which variant the value holds
- ✗Modelling mutually exclusive states as a struct with flags and
Optionfields
Follow-up questions
- →How large is an enum value in memory, and why is
Option<&T>no larger than&T? - →How do you turn a fieldless variant into an integer, and why does the reverse need a function?
JuniorTheoryCommonWhat does the program print?
What does the program print?
12
Open full question →Common mistakes
- ✗Expecting
9: a pattern checks the variant before it binds anything, soShape::Square(a)does not fitShape::Rect(3, 4), and theRect(w, h)arm runs instead. - ✗Expecting an error because
wandhare never declared: a pattern declares the variables it names and fills them with the variant's data.
Follow-up questions
- →What does the program print if it matches
shapes[1]instead? - →What happens if you delete the
Shape::Squarearm?
JuniorTheoryCommonHow does match work, why must it be exhaustive, and what does _ do?
How does match work, why must it be exhaustive, and what does _ do?
match tries arms top to bottom, runs the first whose pattern fits and binds its data. Every possible value needs an arm or the build fails with E0004, so a new variant breaks each match that misses it. _ catches the rest and mutes that check.
Common mistakes
- ✗Thinking a value with no arm is skipped, as in a C
switchwithoutdefault - ✗Treating a missing variant as a warning or a run-time panic instead of error E0004
- ✗Adding
_to everymatchon one's own enum, which hides newly added variants
Follow-up questions
- →Why does the compiler warn when
_stands above other arms? - →Why does a
matchon ani32usually end with a catch-all arm?
JuniorTheoryCommonWhat does the program print?
What does the program print?
small
Open full question →Common mistakes
- ✗Expecting
negativebecausexfits any number: the guardif x < 0is part of the arm, and the arm runs only when the pattern fits and the guard is true. - ✗Expecting
largeby reading1..=9as the two values 1 and 9: a range pattern covers every value between its ends, and..=includes the 9.
Follow-up questions
- →What does the program print for
n = -3and forn = 10? - →Why does the
matchstop compiling if the_arm is removed?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
right, as ifmatchsilently skipped values with no arm:matchmust cover every variant, so leaving outDir::Leftis error E0004. - ✗Expecting a panic when the loop reaches
Left: exhaustiveness is checked while building, so no program is produced at all.
Follow-up questions
- →Which two ways can you change the
matchso that the program compiles? - →Why is naming
Dir::Leftexplicitly better here than adding an_arm?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
Some(6):+does not reach inside anOption, and Rust has no arithmetic onOption<i32>, sox + 1is error E0369 until the value is taken out ofSome. - ✗Expecting
6, as ifSome(5)were simply 5:Option<i32>andi32are different types, and the compiler never uses one in place of the other.
Follow-up questions
- →How would you take the value out of
xso that the program prints6? - →What does
x.unwrap() + 1do whenxisNone?
JuniorTheoryCommonWhy has Rust no null, and how does Option<T> take its place?
Why has Rust no null, and how does Option<T> take its place?
Absence is in the type: a value that may be missing is an Option<T>, Some(v) or None, while a plain T is always there. Option<i32> is not an i32, so you must handle None before use, and null errors become compile errors.
Common mistakes
- ✗Thinking
Noneis a null pointer that any reference may hold - ✗Expecting an
Option<i32>to work wherever ani32is expected - ✗Believing only references lose
nullwhile plain values can still be empty
Follow-up questions
- →What happens when
unwrap()meets aNone, and when is that acceptable? - →Why does
let n = None;without a type annotation fail to compile?
MiddleTheoryCommonWhen do if let, while let and let … else beat match, and what is lost?
When do if let, while let and let … else beat match, and what is lost?
if let handles one variant, while let loops while the pattern fits, and let … else binds for the rest of the block or must leave. Edition 2024 let chains join patterns and conditions with &&. All of them drop the exhaustiveness check.
Common mistakes
- ✗Thinking
if letstill checks that every variant is handled - ✗Writing a
let … elsewhoseelseblock does not leave withreturn,break,continueor a panic - ✗Using let chains in an edition-2021 crate, where they do not compile
Follow-up questions
- →Why must the
elseblock oflet … elsediverge, while theelseofif letneed not? - →How would you rewrite two nested
if letblocks as one let chain?
JuniorDebuggingOccasionalFix a let Some(…) = …; binding that fails with a refutable-pattern error
Fix a let Some(…) = …; binding that fails with a refutable-pattern error
Some((_, value)) is refutable: it fails when split_once returns None, and a plain let accepts only patterns that always fit, hence E0005. Write let Some((_, value)) = … else { return ""; };; if let or match work too.
Common mistakes
- ✗Reaching for
unwrap(), which compiles but panics on a line without= - ✗Writing an
elseblock that yields a value instead of leaving withreturn,break,continueor a panic - ✗Adding a type annotation, although the error is about a pattern that can fail, not about the type
Follow-up questions
- →Why does
let (key, value) = pair;compile whilelet Some(v) = opt;does not? - →When is a
matcha better fix here thanlet … else?
MiddleCodeOccasionalWrite a match over a nested event enum with guards, @ and or-patterns
Write a match over a nested event enum with guards, @ and or-patterns
One match with nested patterns: Key(Char(d @ '0'..='9')) tests and binds the digit, Key(Enter | Esc) joins two keys, Click { x: 0, y: 0, .. } checks fields and skips the rest, and Resize(w, h) if w == h adds a guard. General arms go last.
Common mistakes
- ✗Writing the
@binding after the range: the name comes first, as ind @ '0'..='9' - ✗Expecting guards to count toward exhaustiveness and dropping the plain fallback arm
- ✗Putting a general arm such as
Click { x, y, .. }above the specific ones, which makes them unreachable
Follow-up questions
- →Why must both sides of an or-pattern bind the same names with the same types?
- →Why do
d,xandybecome references when thematchis on a&Event?
MiddleCodeOccasionalRewrite null-style is_none and unwrap checks with Option combinators
Rewrite null-style is_none and unwrap checks with Option combinators
Each is_none test plus unwrap becomes a step of a chain: and_then for a step that can itself give None (the email, the @), map for one that cannot, and unwrap_or_else for the fallback. A helper using ? returns the same Option.
Common mistakes
- ✗Using
mapfor a step that itself returns anOption, which yieldsOption<Option<T>> - ✗Applying
?to anOptioninside a function that returnsStringrather thanOption - ✗Writing
unwrap_or(expensive()), whose argument is computed even when the value isSome
Follow-up questions
- →How would you return a
Resultthat names the failed step, usingok_or? - →Why does
unwrap_or_elsetake a closure whileunwrap_ortakes a value?