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.

RustResilience

Code

rustsnippet
36 lines
#[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

FAQ

How do you run Match Tuples To Combine State Dimensions?
Just run the file; everything it needs ships with the runtime itself.