Rust Day 11
The match control flow Construct
Rust Day 11
The match control flow Construct
match allows you to compare a value against a series of patterns and then execute code based on which pattern matches.
We can write a function that takes an unknown US coin and, in a similar way as the counting machine, determines which coin it is and returns its value in cents:
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
fn main() {}
The match arms. An arm has two parts: a pattern and some code. The first arm here has a pattern that is the value Coin::Penny and then the => operator that separates the pattern and the code to run. The code in this case is just the value 1. Each arm is separated from the next with a comma.
If you want to run multiple lines of code in a match arm, you must use curly brackets, and the comma following the arm is then optional.
For example, the following code prints “Lucky penny!” every time the method is called with a Coin::Penny, but it still returns the last value of the block, 1:
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => {
println!("Lucky penny!");
1
}
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
fn main() {}
Patterns that bind to values
Trying to store an enum inside another enum . The Quarter variant include a UsState value stored inside it.
#[derive(Debug)]
enum UsState {
Alabama,
Alaska,
// --snip--
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
fn main() {}
In the match expression for this code, we add a variable called state to the pattern that matches values of the variant Coin::Quarter. When a Coin::Quarter matches, the state variable will bind to the value of that quarter’s state. Then, we can use state in the code for that arm, like so:
#[derive(Debug)]
enum UsState {
Alabama,
Alaska,
// --snip--
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter(state) => {
println!("State quarter from {state:?}!");
25
}
}
}
fn main() {
value_in_cents(Coin::Quarter(UsState::Alaska));
}
// Let me represent the functino call in an expanded way :
value_in_cents( // Call the function
Coin::Quarter( // Functino takes Coin type as argument; since Coin is an enum
// we must choose one of it's variants using (::) operator
// After choosing Quarter variant ... it also stores an enum
UsState::Alaska // We need to selet one of the variants from UsState enum
)
);

메타데이터
- post_id
- d6c652cc8152
- slug
- rust-day-11-d6c652cc8152
- url
- https://medium.com/@zoolpher/rust-day-11-d6c652cc8152
- canonical_url
- https://medium.com/@zoolpher/rust-day-11-d6c652cc8152
- author_url
- https://medium.com/@zoolpher
- status
- ok
- fetched_at
- 2026-07-13 06:23:13