0
0
Rustprogramming~5 mins

Basic match usage in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ACauses a compile error
BMatches only zero
CMatches any value not matched before
DMatches only negative numbers
Which of these is a valid match arm syntax?
Aif 1 { println!("One") }
Bcase 1: println!("One")
Cwhen 1 => println!("One")
D1 => println!("One")
What will this code print?<br>
let x = 3;
match x {
  1 => println!("One"),
  2 => println!("Two"),
  _ => println!("Other"),
}
AOther
BOne
CTwo
DCompile error
Can match be used to assign a value to a variable?
AYes, because <code>match</code> is an expression
BNo, <code>match</code> only controls flow
COnly if you use <code>if</code> inside <code>match</code>
DOnly with <code>return</code>
What happens if you forget to cover all cases in a match?
ARust compiles silently
BRust gives a compile error
CRust compiles but warns
DRust runs but panics at runtime
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.