Recall & Review
beginner
What is the purpose of the
match statement in Rust?The
match statement lets you compare a value against many patterns and execute code based on which pattern matches. It's like a more powerful switch in other languages.Click to reveal answer
beginner
How do you write a simple
match expression to check if a number is 1, 2, or something else?Example:<br>
match number {
1 => println!("One"),
2 => println!("Two"),
_ => println!("Other"),
}<br>The underscore _ means "anything else".Click to reveal answer
beginner
What does the underscore
_ pattern mean in a match?It means "match anything else". It's a catch-all pattern used when you don't want to specify all possible cases.
Click to reveal answer
intermediate
Can
match return a value in Rust? How?Yes! <code>match</code> is an expression, so it returns the value of the matched arm. For example:<br><pre>let result = match x {
1 => "one",
_ => "other",
};</pre>Click to reveal answer
beginner
What happens if you don't cover all possible cases in a
match?Rust will give a compile error because
match must be exhaustive. You must cover all cases or use _ to catch the rest.Click to reveal answer
What does the
_ pattern do in a Rust match?✗ Incorrect
The underscore
_ is a catch-all pattern that matches any value not matched by previous arms.Which of these is a valid
match arm syntax?✗ Incorrect
Rust uses the syntax
pattern => expression in match arms.What will this code print?<br>
let x = 3;
match x {
1 => println!("One"),
2 => println!("Two"),
_ => println!("Other"),
}✗ Incorrect
Since 3 matches no specific arm, the
_ arm runs, printing "Other".Can
match be used to assign a value to a variable?✗ Incorrect
match returns the value of the matched arm, so you can assign it to variables.What happens if you forget to cover all cases in a
match?✗ Incorrect
Rust requires
match to be exhaustive and will not compile if some cases are missing.Explain how the
match statement works in Rust and why it is useful.Think about how <code>match</code> compares values and handles all possibilities.
You got /4 concepts.
Write a simple Rust
match expression that prints "small" for 1 or 2, "medium" for 3 or 4, and "large" for anything else.Use | to combine patterns for the same arm.
You got /4 concepts.