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 errorAll lessons in this course
- The Builder Pattern
- The Newtype Pattern
- Type-State Builders
- Deref and Wrapper Ergonomics