Match Tuples To Combine State Dimensions
A tuple match dispatches on status and attempt count together: one arm pairs a variant with a concrete value and guards refine the boundary.
Code
#[derive(Debug, Clone, Copy)]
enum Status {
Queued,
Running,
Failed,
}
struct Job {
status: Status,
attempts: u32,
}
const MAX_ATTEMPTS: u32 = 3;
// tuple match:把两个状态维度合成一次分派
fn action(job: &Job) -> &'static str {
match (job.status, job.attempts) {
(Status::Queued, _) => "enqueue",
(Status::Running, _) => "wait",
(Status::Failed, 0) => "invalid state",
(Status::Failed, a) if a < MAX_ATTEMPTS => "retry",
(Status::Failed, _) => "give up",
}
}
fn main() {
let jobs = [
Job { status: Status::Queued, attempts: 0 },
Job { status: Status::Running, attempts: 1 },
Job { status: Status::Failed, attempts: 1 },
Job { status: Status::Failed, attempts: 3 },
];
for job in &jobs {
println!("{:?} x{} -> {}", job.status, job.attempts, action(job));
}
}Inside the snippet
Count the functions action and main as the entire surface area of Match Tuples To Combine State Dimensions.
The one repetition in this snippet is the loop for job in &jobs. match here is the control flow: arms enumerate the value’s shapes exhaustively.
Putting it to use
The primary signature is fn action(job: &Job) -> &'static str
Running the file executes main, which drives action in order.
Core lines
fn action(job: &Job) -> &'static str {
match (job.status, job.attempts) {
(Status::Queued, _) => "enqueue",
(Status::Running, _) => "wait",
(Status::Failed, 0) => "invalid state",
(Status::Failed, a) if a < MAX_ATTEMPTS => "retry",
(Status::Failed, _) => "give up",
}
}
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.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- How do you run Match Tuples To Combine State Dimensions?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.