Hasty Briefsbeta

Bilingual

Parse, Don't Validate and Type-Driven Design in Rust

3 hours ago
  • #Type-Driven Design
  • #Rust
  • #Functional Programming
  • The article discusses the 'parse, don't validate' approach in Rust, emphasizing encoding invariants in types rather than validating data at runtime.
  • It introduces the concept of newtypes (like NonZeroF32 and NonEmptyVec) to ensure certain properties (e.g., non-zero, non-empty) at compile time.
  • The article contrasts validation (checking data at runtime) with parsing (converting data into types that inherently guarantee certain properties).
  • Examples include String as a newtype over Vec<u8> with UTF-8 validation and serde_json's use of types to ensure JSON schema compliance.
  • Key lessons include making illegal states unrepresentable and proving invariants as early as possible to avoid runtime errors.
  • The article advocates for leveraging Rust's type system for safer, more robust code, though acknowledges ergonomic challenges with newtypes.