实现说明
函数 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));
}
}