0
0
Rustprogramming~20 mins

Match expression deep dive in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Rust Match Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Rust match expression?

Consider the following Rust code snippet. What will it print?

Rust
let x = Some(5);
match x {
    Some(n) if n > 3 => println!("Greater than 3: {}", n),
    Some(n) => println!("Some number: {}", n),
    None => println!("No value"),
}
ANo value
BCompilation error
CSome number: 5
DGreater than 3: 5
Attempts:
2 left
💡 Hint

Look at the if guard in the first arm and the value inside Some.

Predict Output
intermediate
2:00remaining
What does this nested match expression print?

Analyze the nested match expression below. What will be printed?

Rust
let value = (2, Some(4));
match value {
    (x, Some(y)) if x == y => println!("Equal: {}" , x),
    (x, Some(y)) => println!("Not equal: {} and {}", x, y),
    _ => println!("No match"),
}
ANot equal: 2 and 4
BEqual: 2
CNo match
DRuntime panic
Attempts:
2 left
💡 Hint

Check the tuple values and the if guard condition.

Predict Output
advanced
2:00remaining
What is the output of this match with shadowing and ref binding?

Consider this Rust code using ref and variable shadowing in a match. What will it print?

Rust
let x = 5;
match x {
    ref r => println!("Got a reference to {}", r),
}
ACompilation error: cannot use ref here
BGot a reference to &5
CGot a reference to 5
DRuntime error
Attempts:
2 left
💡 Hint

Remember that ref creates a reference to the matched value.

Predict Output
advanced
2:00remaining
What is the output of this match with multiple patterns and ranges?

What will this Rust code print?

Rust
let num = 7;
match num {
    1 | 3 | 5 | 7 | 9 => println!("Odd number"),
    2..=8 => println!("Between 2 and 8"),
    _ => println!("Other number"),
}
ACompilation error
BOdd number
COther number
DBetween 2 and 8
Attempts:
2 left
💡 Hint

Check the order of patterns and which one matches first.

Predict Output
expert
3:00remaining
What is the output of this complex match with nested enums and guards?

Given the following Rust enums and match, what will be printed?

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

let msg = Message::Move { x: 10, y: 20 };

match msg {
    Message::Move { x, y } if x == y => println!("Move diagonally to ({}, {})", x, y),
    Message::Move { x, y } => println!("Move to ({}, {})", x, y),
    Message::Write(text) => println!("Text message: {}", text),
    Message::Quit => println!("Quit message"),
    _ => println!("Other message"),
}
AMove to (10, 20)
BMove diagonally to (10, 20)
CText message: Move to (10, 20)
DQuit message
Attempts:
2 left
💡 Hint

Look carefully at the if guard condition and the values of x and y.