← 中文资源

简体中文版本

元组模式加守卫分发路由

match 一次对齐 method 与 path 两个维度,守卫收窄前缀提取资源 id,未登记的动词落进兜底分支被明确拒绝而不是静默放过。

阅读英文原文

实现说明

函数 dispatch、main承担主要逻辑,其余部分只做调用安排。 for (method, path) in routes 承担全部的逐项处理。match 表达式是穷尽的——编译器强制没有遗漏的分支。

使用要点

  • 运行整个文件:main 会依次驱动 dispatch。

常见问题

「元组模式加守卫分发路由」这个示例怎么运行?

把它当完整程序编译/解释运行即可——不需要先安装任何东西。

入口签名:fn dispatch(method: &str, path: &str) -> String

核心语句

("GET", p) if p.starts_with("/users/") => {
    let id = p.trim_start_matches("/users/");
    format!("200 user {id}")
}

代码示例

fn dispatch(method: &str, path: &str) -> String {
    // tuple pattern matches both segments at once; a guard narrows the prefix
    match (method, path) {
        ("GET", "/health") => "200 ok".to_string(),
        ("GET", p) if p.starts_with("/users/") => {
            let id = p.trim_start_matches("/users/");
            format!("200 user {id}")
        }
        ("POST", "/users") => "201 created".to_string(),
        ("GET", _) => "404 not found".to_string(),
        _ => format!("405 method {method} not allowed"),
    }
}

fn main() {
    let routes = [
        ("GET", "/health"),
        ("GET", "/users/42"),
        ("POST", "/users"),
        ("GET", "/metrics"),
        ("DELETE", "/users/42"),
    ];
    for (method, path) in routes {
        println!("{method} {path} -> {}", dispatch(method, path));
    }
}