December 5, 2025
Hold the panic, extra toppings
Patterns for Defensive Programming in Rust
Rust fans swoon over safer code, then argue about pizza and buttons
TLDR: A practical Rust guide shows how to let the compiler catch everyday logic mistakes. Fans praised its real-world tips, while debates erupted over using TryFrom vs From, modeling pizza equality, and replacing confusing booleans with enums—proof that safer code can be spicy and important.
The author hunts down the dreaded “this should never happen” comment and shows how, in Rust, it totally can—unless you make the compiler your bodyguard. With simple tricks like slice pattern matching (so empty lists don’t crash) and explicitly setting every field instead of blindly using defaults, the piece screams: let the compiler enforce your rules. It even gets tasty with a pizza example—comparing orders by toppings and crust, not the order time—sparking a flurry of nods and nitpicks.
The crowd loved it. empath75 called it “one of the best” because it tackles real-world business logic, not wizardly “unsafe” stuff. ggirelli fell for the “temporary mutability” move like it was a magic trick. Then the pedants parachuted in: brohee reminded everyone that TryFrom exists and the From docs now spell out when to use what (link), turning the thread into a mini standards summit. stouset had a “minor nit” about the pizza equality example, arguing the domain model should reflect which fields matter. Meanwhile, J_Shelby_J asked how to ditch confusing boolean flags in favor of enums without losing that sweet yes/no vibe. Jokes flew about pizza toppings and panic-free slices—because in Rust-land, even dinner is a code review.
Key Points
- •Implicit invariants like bounds checks can fail if not enforced by the compiler, despite Rust’s memory safety guarantees.
- •Slice pattern matching ties element access to control flow, preventing out-of-bounds panics and forcing handling of all cases.
- •Using ..Default::default() can hide unintended defaults; prefer explicit field initialization or destructuring a default instance.
- •Destructuring defaults preserves central default logic while ensuring the compiler flags newly added fields and clarifies overrides.
- •Custom equality should compare only business-relevant fields; destructuring helps enforce intended API semantics.