How to Use the Newtype Pattern in Rust

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
}