tezvyn:

The Newtype Pattern: Type Safety for Primitives

AI-drafted, machine-checkedSource: doc.rust-lang.orgintermediate

Wrap a primitive type in a new struct to give it a unique, compile-time identity. A `Miles(f64)` is different from a `Kilometers(f64)`. Use it to prevent mixing up IDs or units. The footgun: you must explicitly implement or delegate methods for the new type.

WHY IT EXISTS To solve the problem of "primitive obsession," where using basic types like i32 or f64 for distinct domain concepts leads to logical errors the compiler can't catch. If a User ID and a Product ID are both i64, you can accidentally pass one where the other is expected. The newtype pattern prevents this.

THE MENTAL MODEL Think of it as putting a specific label on a generic box. A box containing an f64 is just a number. A box labeled Miles containing an f64 is a specific kind of distance. A box labeled Kilometers is a different kind. The compiler reads the labels and stops you from mixing them up, enforcing correctness at compile time.

HOW IT WORKS You define a tuple struct with a single field, like struct Miles(f64);. This creates a new, distinct type that wraps the primitive. The Rust compiler will now enforce that a function expecting Miles cannot be passed a raw f64 or a different newtype like Kilometers(f64). You can then implement methods specifically for your new type, like to_kilometers(), or implement standard traits. To get the inner value back, you use tuple access (my_miles.0) or destructuring (let Miles(val) = my_miles;).

WHEN TO USE IT Use it whenever a primitive type represents a specific domain concept. This is common for database IDs (UserID(i32)), units of measurement (Celsius(f32)), or any value where the type provides meaning beyond its raw representation. It makes function signatures more expressive and your code safer.

WHEN NOT TO USE IT Avoid it for simple values where the context is unambiguous and there's no risk of confusion. Overusing it can add boilerplate, as you often need to implement or derive common traits (Debug, Display, Clone, arithmetic traits) to make the newtype as ergonomic as the primitive it contains.

ONE CANONICAL EXAMPLE A function is_a_marathon(distance: &Miles) requires a distance in miles. If you have a Kilometers value, you cannot pass it directly; the compiler will throw a type mismatch error. You must explicitly convert it first, for example, by calling a method like distance_km.to_miles(). This prevents the logical error of checking if 42 kilometers is a marathon without the required unit conversion.

Read the original → doc.rust-lang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.