Rust If and Match
if is an expression: it can produce a value. match compares a value against patterns and must cover every case.
ExampleRust
fn main() {
let score = 72;
if score >= 90 {
println!("A");
} else if score >= 70 {
println!("B");
} else {
println!("C");
}
let result = if score >= 50 { "pass" } else { "fail" };
println!("{}", result);
let day = 3;
let name = match day {
1 => "Monday",
2 | 3 => "Tuesday or Wednesday",
4..=5 => "Late week",
_ => "Weekend",
};
println!("{}", name);
}Output
B pass Tuesday or Wednesday
The _ pattern matches anything left over. Rust forces match to be exhaustive, so you cannot forget a case.
Quick check
What must a match expression do?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.