In Praise of Exhaustive Destructuring
2 days ago
- #Destructuring
- #Rust
- #Software Safety
- The author initially disliked Rust's requirement to list all fields or use '..' when destructuring structs, finding it less convenient than TypeScript or Haskell.
- They later realized that explicit struct destructuring (listing all fields without '..') enhances software safety by forcing updates when new fields are added.
- Adding a 'wind_speed' field to WeatherReading without updating a function that uses field access ('.' syntax) can lead to bugs without compiler warnings.
- Using struct destructuring in function parameters or within methods triggers a compile-time error if new fields are omitted, ensuring all fields are considered.
- This technique is particularly useful in multi-layered applications (like CRUD services) to ensure consistency when fields are added or changed.
- Observing frequently destructured field groups can indicate a need for refactoring into separate structs to improve design.