Skip to content
tezvyn:
Menu

The Newtype Pattern: Type Safety for Primitives

Source: doc.rust-lang.orgMediumHow cards are made

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.

Interview question

What is the primary benefit of using the Newtype Pattern?

  • a.It allows the compiler to enforce type safety between conceptually distinct primitive values.Correct
  • b.It eliminates the need for explicit conversions between related units of measurement.
  • c.It automatically implements all standard traits for the new type.
  • d.It reduces the memory footprint of primitive data types.
Why?

The Newtype Pattern's main purpose is to give primitive types a unique, compile-time identity, allowing the compiler to catch logical errors where distinct domain concepts might otherwise be accidentally interchanged. Option B is incorrect because the pattern explicitly requires conversions between newtypes, as shown in the example of converting Kilometers to Miles.

Just read this? Test yourself on what you have been reading.

Read the original → doc.rust-lang.org

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on rust — each one lists the topics its interview covers.

See open roles