How to Use the Newtype Pattern for Type Safety in Rust

Wrap existing types in a tuple struct to create distinct types that prevent accidental misuse at compile time.

Use the newtype pattern by wrapping an existing type in a tuple struct to create a distinct type that the compiler treats as incompatible with the original.

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

fn add_meters(m: Meters) -> u32 {
    m.0
}

fn main() {
    let m = Meters(5);
    let mm = Millimeters(5);
    // This compiles: add_meters(m);
    // This fails: add_meters(mm); // Error: expected Meters, found Millimeters
}

This prevents accidental misuse of values like passing meters where millimeters are expected, even though both wrap u32.