Lesson 2 · Unit 02
Pattern matching
Cover every case, and take values apart by shape
What you practise
matchmust cover every case, destructuring,Optioninstead of null,if letandlet else
Try a question from this lesson
Pick one
This match forgot one of the three lights. Python would find out at run time. What does Rust do?
enum Light { Red, Amber, Green }
fn go(l: Light) -> bool {
match l {
Light::Red => false,
Light::Green => true,
}
}Correct answer
Refuses to compile: Amber is not covered
Why
A match must be exhaustive. The error is "non-exhaustive patterns: Light::Amber not covered", reported on line 3. Add a variant later and the compiler lists every match that needs updating.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
match covers every case
match compares a value against patterns from top to bottom and runs the first arm that fits. It is an expression: every arm must produce the same type.
| joins alternatives and _ matches anything. With _ as the last arm the match is always complete, but the compiler can no longer tell you about a case you forgot.
let n = 3;
let name = match n {
1 => "one",
2 | 3 => "few",
_ => "many",
};
println!("{name}");Concept
Option instead of null
In Python any variable might be None, and you find out when it crashes. Rust has no null.
A value that may be missing has the type Option<T>, an enum with two variants: Some(value) or None. An Option<i32> is not an i32. You must take it apart before using the number, so the missing case cannot be forgotten.
let v = vec![10, 20];
let a = v.get(1);
let b = v.get(5);
println!("{:?} {:?}", a, b);10 more exercises in the app
- 4× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.