Control Flow
Match
Selecting by Value
match compares a value against patterns and runs the first arm that fits. _ is the catch-all.
Program
Play the program to map a numeric code to a label.
match_value.rs
Replay: real traced execution (multi-file project)
fn main() {
let code = 2;
let label = match code {
1 => "one",
2 => "two",
_ => "many",
};
println!("{label}");
}
code ← 2, label ← "two"
1fn main() {2 let cod→ 2e = 2;3 let labe→ "two"l = match cod2e {4 1 => "one",5 2 => "two",6 _ => "many",7 };8 println!("{label}");9}outputtwo
Follow the Match
codestarts at2.matchcomparescodeagainst its arms.- The selected arm is
2 => "two". labelbecomestwo.- The program prints
two. | code | selected arm | label | | --- | --- | --- | | 2 |2 => "two"| two |
match
`match` picks one arm based on the value.
arm
Each `pattern => value` is one arm.
wildcard
`_` matches anything not already handled.
Exercise: match_value.rs
Reproduce the output two, then identify the match arm that creates the label.