0
0
Rustprogramming~10 mins

Why pattern matching is needed in Rust - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print a message based on the number using pattern matching.

Rust
let number = 1;
match number {
    [1] => println!("One"),
    2 => println!("Two"),
    _ => println!("Other"),
}
Drag options to blanks, or click blank then click option'
A4
B3
C0
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using a number that does not match the variable value.
Forgetting the underscore (_) pattern for other cases.
2fill in blank
medium

Complete the code to match a character and print its type.

Rust
let ch = 'a';
match ch {
    [1] => println!("Vowel"),
    'b' | 'c' => println!("Consonant"),
    _ => println!("Other"),
}
Drag options to blanks, or click blank then click option'
A'o'
B'a'
C'd'
D'e'
Attempts:
3 left
💡 Hint
Common Mistakes
Using double quotes instead of single quotes for characters.
Choosing a character not listed in the match arms.
3fill in blank
hard

Fix the error in the match pattern to correctly match the tuple.

Rust
let pair = (0, -2);
match pair {
    ([1], y) if y < 0 => println!("Negative y"),
    _ => println!("Other"),
}
Drag options to blanks, or click blank then click option'
A0
Bx
C_
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name instead of a literal for the first element.
Not using a guard condition to check if y is negative.
4fill in blank
hard

Fill both blanks to create a pattern that matches a Some variant with a positive number.

Rust
let value = Some(5);
match value {
    Some([1]) if [2] > 0 => println!("Positive number"),
    _ => println!("Other"),
}
Drag options to blanks, or click blank then click option'
Ax
Cy
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in the pattern and guard.
Using a literal instead of a variable in the pattern.
5fill in blank
hard

Fill all three blanks to destructure a struct and print its fields.

Rust
struct Point { x: i32, y: i32 }
let p = Point { x: 10, y: 20 };
match p {
    Point { [1]: a, [2]: b } if a < b => println!("x < y"),
    Point { [3]: _, y } => println!("Other case"),
}
Drag options to blanks, or click blank then click option'
Ax
By
Dz
Attempts:
3 left
💡 Hint
Common Mistakes
Using a field name that does not exist in the struct.
Using the same variable name for different fields.