← 中文资源

简体中文版本

match 月份天数或模式分组

用或模式把 31 天月份归为一臂、30 天月份归为另一臂,二月按闰年规则分支,范围外月份落到通配臂返回 None,闰年 2 月为 29 天。

阅读英文原文

实现说明

逻辑集中在函数 days_in_month、main里。 驱动整个流程的是 for (year, month) in [(2024, 2), (2023, 2), (2024, 7), (2024, 4), (2024, 13)] 这一个循环。match 一条一条覆盖值的形态——不会意外落到默认分支上。

使用要点

  • main 按顺序串起 days_in_month;运行文件就会把这个流程跑一遍。

常见问题

「match 月份天数或模式分组」这个示例怎么运行?

直接执行即可——程序只依赖运行时自身。

主要签名是 fn days_in_month(year: u32, month: u32) -> Option<u32>

核心语句

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 })
}

代码示例

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"),
        }
    }
}