Rusty thoughts on "Parse, don't validate"
8 hours ago
- The article reviews the 'Parse, don't validate' pattern in Rust, emphasizing using types to enforce invariants instead of runtime checks.
- A key example is replacing Vec<T> with a NonEmpty<T> type that guarantees non-emptiness, eliminating repeated Option handling (e.g., first() returns &T directly).
- Other Rust examples include NonZero<usize> for avoiding zero checks, AbsPathBuf for absolute paths, and serde deserialization that encodes validated types.
- The pattern improves type safety, clarity, and performance (e.g., Option<NonZeroUsize> has same size as usize due to niche optimization).
- Dynamic languages like Python/JS often require manual validation, whereas Rust's type system allows compile-time enforcement.