Match Tuple Guards Route Dispatch
Dispatch routes by matching a method and path tuple, with a guard narrowing the id prefix and a wildcard arm rejecting verbs the router does not accept.
Code
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));
}
}Match Tuple Guards Route Dispatch: reading the source
The edit surface comes down to dispatch and main — the remainder is wiring.
One loop does the cycling here: for (method, path) in routes. A match spells out every case; omit one and the code does not compile.
Caveats
- Nothing depends on a registry or lockfile — it is dependency-free by design.
Using it
Entry signature: fn dispatch(method: &str, path: &str) -> String
Execute the file and main walks through dispatch, in that order.
Key statements
("GET", p) if p.starts_with("/users/") => {
let id = p.trim_start_matches("/users/");
format!("200 user {id}")
}
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- How do you run Match Tuple Guards Route Dispatch?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.