Challenge - 5 Problems
Rust Match Guard Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of match with guard on integer
What is the output of this Rust code snippet?
Rust
fn main() {
let x = 7;
match x {
n if n % 2 == 0 => println!("Even"),
n if n % 2 == 1 => println!("Odd"),
_ => println!("Unknown"),
}
}Attempts:
2 left
💡 Hint
Check the value of x and the conditions in the match guards.
✗ Incorrect
The value 7 is odd, so the guard n % 2 == 1 matches and prints "Odd".
❓ Predict Output
intermediate2:00remaining
Match guard with multiple conditions
What will this Rust program print?
Rust
fn main() {
let c = 'g';
match c {
ch if ch.is_ascii_lowercase() && ch < 'm' => println!("First half lowercase"),
ch if ch.is_ascii_lowercase() => println!("Second half lowercase"),
_ => println!("Not lowercase"),
}
}Attempts:
2 left
💡 Hint
Check the character 'g' against the conditions in order.
✗ Incorrect
'g' is lowercase and 'g' < 'm', so the first guard matches.
❓ Predict Output
advanced2:00remaining
Match guard with tuple and shadowing
What is the output of this Rust code?
Rust
fn main() {
let pair = (3, -2);
match pair {
(x, y) if x == y => println!("Equal"),
(x, y) if x + y == 0 => println!("Sum zero"),
_ => println!("No match"),
}
}Attempts:
2 left
💡 Hint
Check the values of x and y and the guards in order.
✗ Incorrect
3 + (-2) == 1, so the second guard is false; the first guard x == y is false; so it prints "No match".
❓ Predict Output
advanced2:00remaining
Match guard with range and variable binding
What will this Rust program print?
Rust
fn main() {
let num = 15;
match num {
n @ 1..=10 if n % 2 == 0 => println!("Even in 1 to 10"),
n @ 11..=20 if n % 3 == 0 => println!("Multiple of 3 in 11 to 20"),
_ => println!("Other"),
}
}Attempts:
2 left
💡 Hint
Check which range 15 falls into and if it is divisible by 3.
✗ Incorrect
15 is in 11..=20 and divisible by 3, so it prints "Multiple of 3 in 11 to 20".
❓ Predict Output
expert3:00remaining
Match guard with enum and complex condition
Given this Rust code, what is the output?
Rust
enum Status { Active(i32), Inactive(i32), } fn main() { let s = Status::Active(10); match s { Status::Active(n) if n > 5 && n < 15 => println!("Active and moderate"), Status::Active(n) if n >= 15 => println!("Active and high"), Status::Inactive(_) => println!("Inactive"), _ => println!("Unknown"), } }
Attempts:
2 left
💡 Hint
Check the enum variant and the value inside it against the guards.
✗ Incorrect
The value is Active(10), which satisfies n > 5 && n < 15, so it prints "Active and moderate".