A deep dive into the Newtype pattern in Rust — single-field structs that wrap an underlying type to enforce semantic distinctions. Covers the difference between newtypes and type aliases, the importance of keeping the inner field private, and two primary use cases: resource handlers (e.g., graph node indices) and validated types (e.g., Email, ValidatedFilter). Also discusses hiding underlying types for semver-compatible library APIs, when NOT to use newtypes (the Color/Channel boilerplate example), and a real-world pitfall from CosmWasm where direct Deserialize on a newtype bypassed address validation. Includes practical guidance on TryFrom, serde integration, and a rule of thumb: if you'd provide a direct From conversion from the underlying type, a newtype probably isn't warranted.
Table of contents
What are newtypes?Why use newtypes?Hiding underlying typeIs a newtype always a goto?Common pitfall – hidden conversionFinal wordSort: