Lecture 14 - Match, again: patterns, arms, and getting the value out
Announcements
Learning objectives
By the end of today, you should be able to:
- Say which arm of a
matchruns for a given value, and why order matters - Say what can go after
match, and what a pattern is - Explain what an arm hands back, and what
returninside an arm does - Get the value out of an
Option, aResult, or your own enum, and use it after thematch - Match on an enum that is a field of a struct, inside a method
Friday's exam: six sections
50 minutes, 100 points. Lectures 1-13. No notes, no devices. Six sections:
1. Quick recall (14 pts, ~5 min). Fill in a blank, one word or one line.
- Example: a
u8holds values from 0 to____ - Practice: Activity 6, Activity 14 Part 2
2. A day of work (10 pts, ~5 min). Shell and git commands for a scenario.
- Example: which command copies a repo from GitHub onto your machine?
- Practice: Activity 2, Discussion 2, the Lecture 2 quiz, Activity 14 Part 1
3. What does this print (16 pts, ~7 min). Trace a short program and write its exact output.
- Example:
let mut n = 1; while n < 20 { n = n * 3; } println!("{}", n); - Practice: Activity 8 Part 1, Activity 14 Part 3, today's "which arm?"
4. Read the error, fix the bug (16 pts, ~8 min). Code with line numbers, plus the compiler's error. Give the line number and the line as it should read.
- Example: line 3 is
fn bump(&self) {, line 4 isself.hits += 1;, and the error iscannot assign to self.hits, which is behind a & reference - Practice: Activity 5, Activity 8 Part 4, today's "does it compile?" and spot the bug
5. Hand-coding (24 pts, ~11 min). Write two functions on paper. Sometimes you write the signature too.
- Example: write
count_negative, which takes[i32; 5]and returns how many are below zero - Practice: Activities 7, 12, 13, Discussion 4, today's "write it" problems
6. Compare two programs (20 pts, ~8 min). Two working programs: time and space complexity, then which you would use and why.
- Example: find the largest number by sorting and taking the last one, or by one pass keeping the biggest so far
- Practice: Activities 9 and 10, Lecture 15's complexity questions
For a complete list of content coverage - see Lecture 15 (Wednesday, and online already)
For even more practice questions - AI can probably riff on these to quiz you in these formats. We can also generate them on the fly in office hours.
Part 1: What match does
A coin sorter
A coin goes in at the top. It slides past a row of slots. It drops through the first one it fits.
match is the same machine:
- One value goes in
- It is checked against each pattern, top to bottom
- The first pattern it fits wins, and that arm runs
- Nothing below it is checked
- Everything has to land in a slot (not allowed to roll off the machine!)
The parts of match
match coin { // the value going in
Coin::Penny => 1, // pattern => what this arm hands back
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
- After
match: a value - Left of
=>: a pattern, a shape the value might have - Right of
=>: an expression, what this arm does or hands back - A comma between arms
What can go after match
Anything that has a value:
match coin { ... } // a variable
match customer.state { ... } // a field of a struct
match divide(10, 2) { ... } // a function call
match "42".parse::<i32>() { ... } // a method call
match n % 2 { ... } // arithmetic
The type of that value decides what the patterns look like. A Coin gets coin patterns. An Option<u32> gets Some(...) and None.
What a pattern is
A pattern is a shape. Some shapes are exact. Some have a hole in them.
| Pattern | What fits | Makes a new variable? |
|---|---|---|
Coin::Dime | exactly that variant | No |
0 | exactly that number | No |
Some(0) | a Some with exactly 0 inside | No |
Some(n) | any Some, whatever is inside | Yes, n |
n | anything at all | Yes, n |
_ | anything at all | No, it throws it away |
A name in a pattern is a hole. Whatever fills the hole gets that name, for that one arm.
Rust has never seen n before. The pattern is what creates it.
Think-pair-share: which arm?
fn describe(winnings: Option<u32>) { match winnings { Some(0) => println!("A: nothing won"), Some(n) if n > 100 => println!("B: big win, {}", n), Some(n) => println!("C: won {}", n), None => println!("D: did not play"), } } fn main() { for w in [Some(5), Some(0), None, Some(250), Some(100)] { describe(w); } }
Which letter prints for each?
Some(5) Some(0) None Some(250) Some(100)
Answer. C, A, D, B, C.
Swap A and C and every Some lands in C, including Some(0). The compiler warns unreachable pattern on A.
Part 2: What comes out of an arm
match hands back a value
The whole match is an expression, so you can store it:
#[allow(dead_code)] enum Coin { Penny, Nickel, Dime, Quarter } fn main() { let coin = Coin::Dime; let cents = match coin { Coin::Penny => 1, Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter => 25, }; println!("{}", cents); }
Every arm hands back the same type. Rust has to know what type cents is before it knows which arm will run.
Note the ; after the closing }. It ends the let, not the match.
An arm can be a block
#[allow(dead_code)] enum Coin { Penny, Nickel, Dime, Quarter } fn main() { let coin = Coin::Quarter; let cents = match coin { Coin::Penny => 1, Coin::Quarter => { println!("Lucky quarter!"); 25 // no semicolon: this is the arm's value }, _ => 0, }; println!("{}", cents); }
The last line of the block, with no semicolon, is what the arm hands back. Same rule as a function body.
Arms that print
match winnings {
Some(n) => println!("won {}", n),
None => println!("did not play"),
}
println! hands back (), which is Rust for "nothing". So every arm here hands back (), the arms agree, and nothing gets stored. Fine.
Think-pair-share: does it compile?
(a)
match coin {
Coin::Penny => println!("1 cent"),
_ => ()
}
(b)
let label = match coin {
Coin::Penny => "small",
Coin::Quarter => 25,
_ => "medium",
};
(c)
let cents = match coin {
Coin::Penny => 1,
Coin::Quarter => {
println!("Lucky!");
25;
}
_ => 0,
};
(d)
fn bonus(level: u32) -> u32 {
match level {
1 => 10,
2 => 20,
3 => 50,
}
}
Answer.
(a) Yes. Both arms return ().
(b) No. match arms have incompatible types.
(c) No. The semicolon after 25 turns it into a statement, so that block hands back () while the others hand back numbers. The compiler even says help: consider removing this semicolon.
(d) No. A u32 has about four billion values, and three arms cover three of them:
error[E0004]: non-exhaustive patterns: `0_u32` and `4_u32..=u32::MAX` not covered
Exhaustive means every possible value, not only enum variants. Add _ => 0 to fix.
Part 3: Getting the value out
The name only lives inside its arm
match find_index("Mei", names) {
Some(i) => println!("found at {}", i),
None => println!("not found"),
}
println!("{}", last_names[i]); // error: cannot find value `i`
i was made by the pattern, so it ends with the arm. Two ways out:
- Hand the value back into a
let, and use it afterwards - Do the work inside the arm
Hand it back into a let
fn ticket_price(age: Option<u32>) -> u32 { let age = match age { Some(a) => a, // hand back what was inside None => return 15, // no age given: full price, and leave now }; // from here on, age is a plain u32 if age < 12 { 8 } else { 15 } } fn main() { println!("{}", ticket_price(Some(9))); println!("{}", ticket_price(Some(40))); println!("{}", ticket_price(None)); }
return inside an arm leaves the whole function, not just the match. The None arm never hands anything to let age, because by then we are gone.
Do the work in an arm
fn ticket_price(age: Option<u32>) -> u32 { match age { Some(a) => if a < 12 { 8 } else { 15 }, None => 15, } } fn main() { println!("{}", ticket_price(Some(9))); println!("{}", ticket_price(Some(40))); println!("{}", ticket_price(None)); }
Or on the pattern side,
fn ticket_price(age: Option<u32>) -> u32 { match age { Some(a) if a < 12 => 8, Some(_) => 15, None => 15, } } fn main() { println!("{}", ticket_price(Some(9))); println!("{}", ticket_price(Some(40))); println!("{}", ticket_price(None)); }
A shape to remember
let value = match something_that_might_not_work {
Some(v) => v, // or Ok(v) => v
None => ..., // or Err(e) => ...
};
The second arm is the decision. Three choices:
- A default:
None => 0 - Give up on this function:
None => return None, orErr(e) => return Err(e) - Crash:
None => panic!("...")
Choice 2, with Result, is exactly what ? writes for you.
The same shape, with Result
fn total_bet(a: &str, b: &str) -> Result<u32, String> { let first = match a.parse::<u32>() { Ok(n) => n, Err(_) => return Err(format!("'{}' is not a bet", a)), }; let second = match b.parse::<u32>() { Ok(n) => n, Err(_) => 0, // the second bet is optional }; Ok(first + second) } fn main() { println!("{:?}", total_bet("10", "5")); println!("{:?}", total_bet("10", "x")); println!("{:?}", total_bet("ten", "5")); }
Ok(15)
Ok(10)
Err("'ten' is not a bet")
Two matches, two different decisions about the error arm.
Think-pair-share: write it
A game has four levels. Each one is Some(coins) if you finished it, None if you did not.
(a) Add up the coins from the levels you finished.
fn total_coins(levels: [Option<u32>; 4]) -> u32 {
// your code here
}
| Call | Returns |
|---|---|
total_coins([Some(3), None, Some(10), Some(0)]) | 13 |
total_coins([None, None, None, None]) | 0 |
(b) If you finish early: the same, but None unless every level was finished.
fn total_if_complete(levels: [Option<u32>; 4]) -> Option<u32> {
// your code here
}
Answer.
fn total_coins(levels: [Option<u32>; 4]) -> u32 { let mut total = 0; for level in levels { match level { Some(coins) => total += coins, None => () } } total } fn total_if_complete(levels: [Option<u32>; 4]) -> Option<u32> { let mut total = 0; for level in levels { match level { Some(coins) => total += coins, None => return None, // any unfinished: give up } } Some(total) } fn main() { println!("{}", total_coins([Some(3), None, Some(10), Some(0)])); println!("{}", total_coins([None, None, None, None])); println!("{:?}", total_if_complete([Some(3), None, Some(10), Some(0)])); println!("{:?}", total_if_complete([Some(3), Some(4), Some(10), Some(0)])); }
The only differences in (b): the None arm returns, and the end wraps total in Some.
Part 4: An enum inside a struct
Back to Alice
Last week we fixed Customer so state is an enum, not a String. Now let's compute her shipping cost:
#![allow(dead_code)] enum State { NY, MA, CA } struct Customer { name: String, state: State, member: bool, } impl Customer { fn shipping_cost(&self) -> f64 { match self.state { State::NY => 5.00, State::MA => 7.50, State::CA => 12.00, } } } fn main() { let alice = Customer { name: String::from("Alice"), state: State::NY, member: false }; println!("{} pays {:.2}", alice.name, alice.shipping_cost()); let _ = alice.member; }
What goes after match? self.state, a field. Its type is State, so the patterns are states.
Outside a method it is the same thing with a different name: match alice.state { ... }.
When the variant carries data
enum Status {
Active,
Injured(u32), // games left to sit out
Retired,
}
struct Player {
name: String,
status: Status,
}
Think-pair-share: write it
Write report, a method on Player that prints one line:
Totoro: active
Mei: injured, games left to sit out: 2
Satsuki: retired
impl Player {
fn report(&self) {
// your code here
}
}
If you're done: Write next_game(&mut self). An injured player has one fewer game to sit out, and is Active again when it reaches zero. Everyone else is unchanged.
Answer.
#![allow(dead_code)] enum Status { Active, Injured(u32), Retired, } struct Player { name: String, status: Status, } impl Player { fn report(&self) { match self.status { Status::Active => println!("{}: active", self.name), Status::Injured(games) => println!("{}: injured, games left to sit out: {}", self.name, games), Status::Retired => println!("{}: retired", self.name), } } fn next_game(&mut self) { match self.status { Status::Injured(1) => self.status = Status::Active, Status::Injured(games) => self.status = Status::Injured(games - 1), _ => () } } } fn main() { let mut mei = Player { name: String::from("Mei"), status: Status::Injured(2) }; mei.report(); mei.next_game(); mei.report(); mei.next_game(); mei.report(); }
games is a hole, same as n in Some(n). self.name comes from the struct, and games comes from the variant.
In the stretch, Injured(1) has to sit above Injured(games), or the general arm catches it first. And it is &mut self because it changes self.status.
Part 5: Spot the bug
Three bugs from real(istic) hand-coding
Each one does not compile. What is wrong, and what is the simplest fix?
find_index returns an Option<usize>
1.
if find_index("Mei", names) == 1 {
println!("Mei is second");
}
2.
match find_index("Mei", names) {
Some(i) => println!("found"),
None => println!("not found"),
}
println!("{}", last_names[i]);
3.
fn half(n: u32) -> Option<u32> {
if n % 2 == 0 {
n / 2
} else {
None
}
}
Answer.
find_indexhands back anOption<usize>, not a number, and anOptionis never equal to1. Compare againstSome(1), or open it with amatchionly exists inside theSomearm. Move theprintln!into that arm- The return type promises an
Option, so the even case needsSome(n / 2).
Part 6: A pep talk for your first code review
What a code review is not
A search for what you got wrong.
The autograder already did that.
What it actually is
Somebody opens your repo, reads your code and your commit history, and asks you why.
Why this approach. What you tried first. What happens if the input changes.
Expect it to be uncomfortable
Remember:
- It is a conversation about choices, not a search for defects
- Not knowing is allowed. But dishonesty will bite you.
"I don't know why that works, I tried it after the other version panicked" is a good answer. It is honest, it says what you did, and it is something we can talk about.
Activity time
See Activity 14
You'll write how you feel, not answers.
You'll take a photo and submit it on gradescope so you can keep the paper for studying.