0
0
Rustprogramming~20 mins

Match guards in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Rust Match Guard Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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"),
    }
}
AOdd
BEven
CUnknown
DCompilation error
Attempts:
2 left
💡 Hint
Check the value of x and the conditions in the match guards.
Predict Output
intermediate
2: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"),
    }
}
AFirst half lowercase
BSecond half lowercase
CNot lowercase
DRuntime panic
Attempts:
2 left
💡 Hint
Check the character 'g' against the conditions in order.
Predict Output
advanced
2: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"),
    }
}
AEqual
BCompilation error
CNo match
DSum zero
Attempts:
2 left
💡 Hint
Check the values of x and y and the guards in order.
Predict Output
advanced
2: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"),
    }
}
AEven in 1 to 10
BOther
CCompilation error
DMultiple of 3 in 11 to 20
Attempts:
2 left
💡 Hint
Check which range 15 falls into and if it is divisible by 3.
Predict Output
expert
3: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"),
    }
}
AActive and high
BActive and moderate
CInactive
DUnknown
Attempts:
2 left
💡 Hint
Check the enum variant and the value inside it against the guards.