Match Days In Month Or Patterns

Group 31-day months with or-patterns, 30-day months with another arm, and let February branch on the leap-year rule inside the match.

RustData Integrity

Code

rustsnippet
24 lines
fn days_in_month(year: u32, month: u32) -> Option<u32> {
    match month {
        // or-patterns group every 31-day month into one arm
        1 | 3 | 5 | 7 | 8 | 10 | 12 => Some(31),
        // the 30-day months share an arm too
        4 | 6 | 9 | 11 => Some(30),
        // February: leap years via the divisible-by-4/100/400 rule
        2 => {
            let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
            Some(if leap { 29 } else { 28 })
        }
        // wildcard arm rejects anything outside 1..=12
        _ => None,
    }
}

fn main() {
    for (year, month) in [(2024, 2), (2023, 2), (2024, 7), (2024, 4), (2024, 13)] {
        match days_in_month(year, month) {
            Some(days) => println!("{year}-{month:02} has {days} days"),
            None => println!("{month} is not a month"),
        }
    }
}

Under the hood — Match Days In Month Or Patterns

The work concentrates inside the functions days_in_month and main.

for (year, month) in [(2024, 2), (2023, 2), (2024, 7), (2024, 4), (2024, 13)] is the loop that carries the per-item work. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Watch out for

  • Zero packages pulled in — the runtime ships every API this code touches.

Using it

Entry signature: fn days_in_month(year: u32, month: u32) -> Option<u32>

Treat main as the orchestrator calling days_in_month in a fixed order.

Key statements

match days_in_month(year, month) {
    Some(days) => println!("{year}-{month:02} has {days} days"),
    None => println!("{month} is not a month"),
}
Some(if leap { 29 } else { 28 })
}

Interactive Tools for This Topic

FAQ

How do you run Match Days In Month Or Patterns?
Run the file on its own; every call resolves against the standard surface it already imports.