Rust Pattern Matching Quiz

Rust
0 Passed
0% acceptance

40 comprehensive questions on Rust's pattern matching system, covering match expressions, destructuring, guards, wildcards, and enum matching — with 11 code examples demonstrating practical pattern matching techniques.

40 Questions
~80 minutes
1

Question 1

What is pattern matching in Rust and why is it important?

A
A way to check if a value matches certain patterns and execute code based on the match, providing compile-time exhaustiveness guarantees
B
A way to compare two values for equality
C
A replacement for if-else statements
D
A way to sort data structures
2

Question 2

What is the basic syntax of a match expression in Rust?

A
match value { pattern => expression, pattern => expression, ... }
B
switch value { case pattern: expression; case pattern: expression; ... }
C
if value matches pattern { expression } else if value matches pattern { expression }
D
match value with pattern => expression, pattern => expression, ...
3

Question 3

What does it mean for a match expression to be exhaustive?

A
Every possible value of the matched type must be covered by at least one pattern
B
The match must handle the most common cases first
C
The match must be optimized for performance
D
The match must use all available patterns
4

Question 4

What will this match expression return?

rust
fn main() {
    let number = 3;
    let result = match number {
        1 => "one",
        2 => "two",
        3 => "three",
        _ => "other",
    };
    println!("Result: {}", result);
}
A
Result: three
B
Result: other
C
Compilation error
D
Runtime error
5

Question 5

What is destructuring in pattern matching?

A
Breaking down complex data structures into their component parts during matching
B
Converting data types during matching
C
Sorting data during matching
D
Validating data during matching
6

Question 6

How do you destructure a tuple in a match expression?

A
Use (var1, var2, ...) => expression to bind tuple elements to variables
B
Use [var1, var2, ...] => expression for tuples
C
Use {var1, var2, ...} => expression for tuples
D
Tuples cannot be destructured in match
7

Question 7

What will this tuple destructuring code output?

rust
fn main() {
    let triple = (1, 2, 3);
    match triple {
        (0, y, z) => println!("First is 0, y = {}, z = {}", y, z),
        (1, y, z) => println!("First is 1, y = {}, z = {}", y, z),
        _ => println!("Something else"),
    }
}
A
First is 1, y = 2, z = 3
B
First is 0, y = 2, z = 3
C
Something else
D
Compilation error
8

Question 8

What are guards in pattern matching and how do you use them?

A
Additional conditions added with 'if' that must be true for a pattern to match
B
Security checks that prevent invalid matches
C
Performance optimizations for matching
D
Type checks for pattern matching
9

Question 9

How do you use a guard in a match expression?

A
pattern if condition => expression
B
pattern where condition => expression
C
pattern && condition => expression
D
Guards cannot be used in match expressions
10

Question 10

What will this code with a guard output?

rust
fn main() {
    let num = 4;
    match num {
        x if x % 2 == 0 => println!("Even number: {}", x),
        x if x % 2 == 1 => println!("Odd number: {}", x),
        _ => println!("Something else"),
    }
}
A
Even number: 4
B
Odd number: 4
C
Something else
D
Compilation error
11

Question 11

What is the underscore (_) wildcard pattern used for?

A
Ignoring values that you don't care about in a pattern
B
Matching any single character
C
Matching zero or more characters
D
Creating default cases
12

Question 12

When should you use the underscore pattern in match expressions?

A
When you want to handle all remaining cases that don't match other patterns
B
When you want to match specific values only
C
When you want to create loops
D
When you want to sort values
13

Question 13

What does the double dot (..) syntax do in patterns?

A
Ignores remaining fields in struct patterns or elements in tuple patterns
B
Creates range patterns for matching
C
Repeats the previous pattern
D
Creates nested patterns
14

Question 14

How do you destructure a struct in a match pattern?

A
Use StructName { field1, field2, .. } => expression
B
Use StructName(field1, field2) => expression
C
Use {field1, field2} => expression
D
Structs cannot be destructured in match
15

Question 15

What will this struct destructuring code do?

rust
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 10, y: 20 };
    match p {
        Point { x: 0, y: 0 } => println!("Origin"),
        Point { x, y } => println!("Point at ({}, {})", x, y),
    }
}
A
Print 'Point at (10, 20)'
B
Print 'Origin'
C
Compilation error
D
Runtime error
16

Question 16

What is enum matching and why is it particularly useful in Rust?

A
Matching on enum variants to handle different cases safely, with compile-time guarantees that all variants are covered
B
Converting enums to other types
C
Sorting enum values
D
Creating enum instances
17

Question 17

How do you match on enum variants in a match expression?

A
Use EnumName::Variant => expression for each variant
B
Use Variant => expression without the enum name
C
Use case EnumName::Variant: expression
D
Enums cannot be matched
18

Question 18

What will this enum matching code output?

rust
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

fn main() {
    let msg = Message::Write(String::from("hello"));
    match msg {
        Message::Quit => println!("Quit"),
        Message::Move { x, y } => println!("Move to ({}, {})", x, y),
        Message::Write(text) => println!("Write: {}", text),
        Message::ChangeColor(r, g, b) => println!("Color: ({}, {}, {})", r, g, b),
    }
}
A
Write: hello
B
Quit
C
Move to (0, 0)
D
Compilation error
19

Question 19

What happens if you don't handle all enum variants in a match expression?

A
Compilation error: pattern is not exhaustive
B
Runtime error
C
The unhandled variants are ignored
D
The match returns a default value
20

Question 20

How do you handle multiple enum variants with the same behavior?

A
Use the | (or) operator: Variant1 | Variant2 => expression
B
Use separate arms for each variant
C
Use guards to combine variants
D
This is not possible
21

Question 21

What is match ergonomics in Rust?

A
Automatic dereferencing and borrowing adjustments in match patterns
B
Automatic code formatting for match expressions
C
Performance optimizations for match expressions
D
Ergonomic keyboard shortcuts for writing match code
22

Question 22

How do you match on references in patterns?

A
Use &pattern for matching references, or let match ergonomics handle it
B
Use *pattern for dereferencing
C
References cannot be matched directly
D
Use ref pattern for references
23

Question 23

What will this reference matching code do?

rust
fn main() {
    let value = Some(42);
    match &value {
        Some(v) => println!("Got {}", v),
        None => println!("Nothing"),
    }
    // value is still accessible here
    println!("Value is still: {:?}", value);
}
A
Print 'Got 42' then 'Value is still: Some(42)'
B
Compilation error
C
Print 'Got 42' then lose access to value
D
Runtime error
24

Question 24

What are match arms and how do they work?

A
Each pattern => expression pair in a match expression, executed when the pattern matches
B
The different branches of a match expression
C
Both A and B are correct
D
The patterns themselves
25

Question 25

How do you use pattern matching with if let for simpler cases?

A
if let pattern = value { ... } else { ... }
B
if value matches pattern { ... }
C
if pattern in value { ... }
D
if let is not used for pattern matching
26

Question 26

What is the difference between match and if let?

A
match requires exhaustive coverage of all cases, if let only handles one pattern
B
match is faster than if let
C
if let requires exhaustive coverage
D
There is no functional difference
27

Question 27

How do you match on ranges of values?

A
Use start..=end for inclusive ranges in patterns
B
Use start..end for exclusive ranges
C
Both A and B work depending on the context
D
Range matching is not supported
28

Question 28

What will this range matching code output?

rust
fn main() {
    let number = 15;
    match number {
        0..=10 => println!("Low"),
        11..=20 => println!("Medium"),
        _ => println!("High"),
    }
}
A
Medium
B
Low
C
High
D
Compilation error
29

Question 29

What is binding in pattern matching?

A
Creating variables that bind to parts of the matched value
B
Connecting patterns to expressions
C
Creating references to matched values
D
Binding is not a pattern matching concept
30

Question 30

How do you use @ bindings in patterns?

A
pattern @ binding_variable to bind the entire matched value to a variable while also destructuring it
B
binding_variable @ pattern for reverse binding
C
@ is not used in Rust patterns
D
pattern & binding_variable for reference binding
31

Question 31

What will this @ binding code demonstrate?

rust
fn main() {
    let msg = Some(42);
    match msg {
        value @ Some(42) => println!("Got the answer: {:?}", value),
        Some(other) => println!("Got something else: {}", other),
        None => println!("Nothing"),
    }
}
A
Print 'Got the answer: Some(42)'
B
Print 'Got something else: 42'
C
Compilation error
D
Print 'Nothing'
32

Question 32

What is the ref keyword used for in patterns?

A
Creating references to parts of the matched value instead of moving them
B
Referencing external variables
C
Creating mutable references
D
ref is not used in patterns
33

Question 33

When should you use ref in match patterns?

A
When you want to borrow parts of the matched value instead of moving them
B
When matching on references
C
When creating mutable bindings
D
ref should never be used in patterns
34

Question 34

What is the mut keyword used for in patterns?

A
Creating mutable bindings to matched parts of the value
B
Making the entire match mutable
C
Allowing mutation of the matched value
D
mut is not used in patterns
35

Question 35

How do you handle complex nested patterns in match expressions?

A
Use nested destructuring with appropriate syntax for each type (tuples, structs, enums)
B
Flatten the structure before matching
C
Use separate match expressions
D
Complex nesting is not supported
36

Question 36

What will this nested pattern matching do?

rust
enum Shape {
    Circle(f64),
    Rectangle(f64, f64),
}

fn main() {
    let shape = Shape::Rectangle(10.0, 20.0);
    match shape {
        Shape::Circle(radius) => println!("Circle with radius {}", radius),
        Shape::Rectangle(width, height) => println!("Rectangle {}x{}", width, height),
    }
}
A
Print 'Rectangle 10x20'
B
Print 'Circle with radius 10'
C
Compilation error
D
Runtime error
37

Question 37

What is the purpose of match expressions returning values?

A
Allowing match to be used in assignments and expressions, not just statements
B
Improving performance
C
Reducing code size
D
Match expressions don't return values
38

Question 38

How do you make match expressions more concise when many arms have the same result?

A
Use the | operator to combine patterns: Pattern1 | Pattern2 => result
B
Use multiple lines for the same arm
C
Use guards to combine conditions
D
This is not possible
39

Question 39

In a scenario where you're implementing a calculator that handles different operations, how would you structure the pattern matching?

A
Use an enum for operations and match on enum variants with destructuring for operands
B
Use if-else chains for each operation
C
Use function pointers for operations
D
Use a hash map of operations
40

Question 40

What advanced pattern matching technique would you use when you need to match a pattern but also keep a reference to the original value for later use?

A
Use @ bindings: pattern @ whole_value to capture both the destructured parts and the complete value
B
Use ref bindings to create references
C
Use guards with additional conditions
D
This requires separate matching operations

QUIZZES IN Rust