Sub topic 17
The newtype pattern
A newtype is a tuple struct with exactly one field. It wraps an existing type so the compiler treats the wrapper as a new type. This chapter assumes you know tuple structs, impl blocks, &self receivers, field privacy, and how to derive traits. Those were covered in earlier chapters.
Why wrap a type
Take two functions that both accept an f64. The compiler cannot tell a distance in meters from one in feet, so passing the wrong one compiles and gives a wrong answer. A newtype moves that mistake from runtime to compile time.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Meters(f64);
#[derive(Debug, Clone, Copy, PartialEq)]
struct Feet(f64);
impl Feet {
fn to_meters(self) -> Meters {
Meters(self.0 * 0.3048)
}
}
fn runway_long_enough(length: Meters) -> bool {
length.0 >= 1500.0
}
fn main() {
let a = Meters(1800.0);
let b = Feet(4000.0);
println!("{}", runway_long_enough(a));
println!("{}", runway_long_enough(b.to_meters()));
// runway_long_enough(b); // error[E0308]: mismatched types
}The program prints true and then false. 4000 feet is about 1219 meters, which is below the limit. The commented-out call would be rejected at compile time.
The wrapper has no runtime cost. A struct with one field has the same size as that field, and the compiler can optimize through it. You pay only in source code.
Replace that stray block: the diagram follows.
What a newtype does not inherit
A newtype has none of the wrapped type's traits or methods. Meters(1.0) + Meters(2.0) fails because Meters does not implement Add, even though f64 does. You choose what to expose. You can derive the traits that derive supports, and you can implement the others by hand.
use std::ops::Add;
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
struct Meters(f64);
impl Add for Meters {
type Output = Meters;
fn add(self, other: Meters) -> Meters {
Meters(self.0 + other.0)
}
}
impl From<f64> for Meters {
fn from(value: f64) -> Self {
Meters(value)
}
}
fn main() {
let total = Meters(1.5) + Meters::from(2.0);
println!("{:?}", total);
println!("{}", total > Meters(3.0));
}This prints Meters(3.5) and then true. Note what is missing: you cannot add a Meters to a Feet, or multiply two Meters values, unless you write those impls. That restriction is the purpose of the pattern.
Working around the orphan rule
Rust's orphan rule says you may implement a trait for a type only if your crate defines the trait or the type. You cannot write impl Display for Vec<String>, because both Display and Vec come from the standard library. A newtype is local, so you can implement the trait on it.
use std::fmt;
struct Wrapper(Vec<String>);
impl fmt::Display for Wrapper {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}]", self.0.join(", "))
}
}
fn main() {
let w = Wrapper(vec![String::from("a"), String::from("b")]);
println!("{}", w);
}The output is [a, b]. The same technique works for any foreign trait on any foreign type.
Enforcing invariants with privacy
A newtype with a private field gives you a type that can only hold valid values. Define it in a module, keep the field private, and offer a constructor that checks the input. Code elsewhere can hold an Email but cannot build one without going through parse.
mod email {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Email(String);
impl Email {
pub fn parse(input: &str) -> Result<Self, String> {
let trimmed = input.trim();
match trimmed.split_once('@') {
Some((user, domain)) if !user.is_empty() && domain.contains('.') => {
Ok(Self(trimmed.to_lowercase()))
}
_ => Err(format!("invalid email: {input}")),
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
}
use email::Email;
fn send_welcome(to: &Email) {
println!("sending to {}", to.as_str());
}
fn main() {
match Email::parse(" [email protected] ") {
Ok(e) => send_welcome(&e),
Err(msg) => println!("{msg}"),
}
println!("{:?}", Email::parse("nope"));
}Output:
sending to [email protected]
Err("invalid email: nope")Any function that takes &Email can assume the value was validated once, at the boundary. It does not need to check again. This is the "parse, don't validate" style.
Outside the email module, Email("x".to_string()) is a compile error because the field is private. If you made the field pub, the guarantee would disappear.
Choosing what to expose
You have three options for reaching the wrapped value. Pick deliberately, because each one decides how much of the inner type leaks out.
| Approach | Example | Effect |
|---|---|---|
| Public field | `pub struct Id(pub u32);` | Anyone can build or read the value. Good for pure type distinction, no invariants. |
| Accessor method | `fn as_str(&self) -> &str` | Read-only access. Keeps invariants. |
| Conversion trait | `impl From<Meters> for f64` | Explicit, conventional exit. Callers write `f64::from(m)`. |
| `Deref` | `impl Deref for Email` | Every method of the inner type becomes callable on the wrapper. |
Common errors
- Forgetting derives.
println!("{:?}", Meters(1.0))fails until you add#[derive(Debug)]. The same goes forClone,Copy,PartialEq, andPartialOrd. A derive on a newtype requires the inner type to implement the trait too. - Using
.0everywhere. If callers keep unwrapping the value to do arithmetic, the wrapper adds noise without safety. Implement the operators you need, or provide methods that keep values wrapped. - Leaving the field public with an invariant. If a constructor validates but the field is
pub, callers can skip the constructor. - Wrapping when an alias would do.
type Meters = f64;creates a second name for the same type. It gives no type safety. Use a newtype when you want the compiler to reject mix-ups. - Forgetting to move or borrow. A newtype around
Stringis notCopy. Passing it by value moves it, so take&Emailwhen you only need to read.
When to use it
Use a newtype for units, identifiers such as UserId(u64) and OrderId(u64), values with rules like emails or non-empty strings, and foreign trait impls. Skip it when the extra type would have no distinct meaning or when you would have to forward most of the inner type's API by hand.
Exercise
You have struct UserId(u64); and struct OrderId(u64);. A function fn cancel(order: OrderId) is called with cancel(UserId(7)). Does this compile? Name one change that lets you build an OrderId from a u64 only through a check that the value is nonzero.
Show answer
It does not compile. UserId and OrderId are distinct types, so the compiler reports a mismatched types error even though both wrap a u64. To enforce the nonzero rule, move OrderId into a module, keep its field private, and add pub fn new(n: u64) -> Option<Self> that returns None when n == 0. Callers can then only get an OrderId through new.
Exercise
Why can't you write impl std::fmt::Display for Vec<i32> in your crate, and how does a newtype fix it?
Show answer
The orphan rule requires either the trait or the type to be defined in your crate. Display and Vec both come from the standard library, so the impl is rejected. Defining struct Numbers(Vec<i32>); makes the type local, so impl Display for Numbers is allowed.