Rust

Lesson 05

Pattern matching exhaustiveness

Match enum states directly so new variants force a review of every state-dependent branch.

Good Code

src/review_status.rs
pub enum ReviewStatus {
    Draft,
    Approved,
    Rejected { reason: String },
}

pub fn status_label(status: &ReviewStatus) -> &'static str {
    // Exhaustive match makes every status visible during review.
    match status {
        ReviewStatus::Draft => "draft",
        ReviewStatus::Approved => "approved",
        ReviewStatus::Rejected { .. } => "rejected",
    }
}

Bad Code

review_status.rs
pub fn status_label(status: &str) -> &'static str {
    // String states let unknown values slip into the default branch.
    match status {
        "draft" => "draft",
        "approved" => "approved",
        _ => "unknown",
    }
}

Review Notes

What to review

Good Code

The good version models status as an enum and matches every variant. Adding a new status creates a compiler-guided review point.

Bad Code

The bad version uses string states and a broad default branch. A misspelled or newly added status becomes "unknown" without forcing a design decision.

Takeaways

  • Rust enum reviews should prefer exhaustive matching over string flags or default branches that hide new states.