What is the newtype pattern

The newtype pattern wraps an existing type in a new tuple struct to create a distinct type for safety and trait implementation.

The newtype pattern is a technique where you wrap an existing type inside a new tuple struct to create a distinct type for type safety or abstraction. It prevents the compiler from confusing similar types (like Millimeters vs Meters) and allows you to implement external traits on the wrapper that you couldn't implement on the inner type directly.

struct Millimeters(u32);
struct Meters(u32);

fn distance(m: Meters) {
    // Cannot accidentally pass Millimeters here
}