0PricingLogin
Learn Rust Coding · Lesson

The Newtype Pattern

Wrap types for safety and clarity.

What Is a Newtype?

A newtype is a single-field tuple struct that wraps an existing type to give it a distinct identity. struct Meters(f64) is a brand new type even though it holds a plain f64.

The wrapper has zero runtime cost but lets the compiler enforce meaning that a raw primitive cannot.

struct Meters(f64);
struct Seconds(f64);

Preventing Unit Mix-Ups

Raw primitives are easy to confuse. If both a distance and a time are f64, nothing stops you swapping them in a call.

Wrapping each in its own newtype makes such mistakes a compile error instead of a silent bug.

fn speed(d: Meters, t: Seconds) -> f64 {
    d.0 / t.0
}
// speed(Seconds(2.0), Meters(10.0)) -> compile error

All lessons in this course

  1. The Builder Pattern
  2. The Newtype Pattern
  3. Type-State Builders
  4. Deref and Wrapper Ergonomics
← Back to Learn Rust Coding