Use the newtype pattern to wrap a type in a tuple struct, creating a unique type for safety and trait implementation.
The newtype pattern wraps an existing type in a tuple struct to create a distinct type for type safety or to implement external traits.
struct Millimeters(u32);
struct Meters(u32);
fn main() {
let x = Millimeters(5);
let y = Meters(5);
// let z = x + y; // Error: cannot add distinct types
}
The newtype pattern is like putting a label on a generic box to tell you exactly what's inside. It prevents you from accidentally mixing up similar values, like adding meters to millimeters, because the computer sees them as completely different things. You use it whenever you need to enforce rules about how data is used or to add specific behavior to a standard type.