When a Simpler Type Is Better
In this post
- Every wrapper is a bet
- What the compiler catches — and what it lets through
- The boilerplate bill
- Markers have a ceiling
- What the standard library wraps
- Criteria
- Where the series lands
Every wrapper is a bet
This post closes a series of eight about putting domain knowledge into Rust’s type system. The earlier posts built the toolkit one piece at a time: smart constructors give values with invariants a type of their own, typestate turns operation order into the type, layout attributes turn memory observations into promises, and the public API post treats every published type as a promise to callers. Each of these tools makes the same kind of trade: someone pays a little convenience — a conversion, an annotation, an extra struct — and in return the compiler refuses a class of mistakes.
The trade is not always worth taking. A wrapper with no invariant to defend adds code but protects against nothing. A marker parameter on a type nobody mixes up is noise. This post prices the tools — what each level catches, what it costs — and ends with the criteria for deciding where to stop. A signup flow supplies the running values: a numeric user id and an email address.
What the compiler catches — and what it lets through
Two u64 values in scope: the id of the current user and a limit on their orders. A function takes both:
fn grant(user_id: u64, max_orders: u64) -> String {
format!("user {user_id} limited to {max_orders} orders")
}
fn main() {
let id = 4000_u64;
let cap = 5_u64;
println!("{}", grant(cap, id)); // arguments swapped by mistake
}
The program compiles and prints user 5 limited to 4000 orders. Every piece of information needed to catch the bug was in the names, and the compiler ignores names. The swap ships.
Distinct one-field types turn the same mistake into a build failure:
struct UserId(u64);
struct OrderLimit(u64);
fn grant(user_id: UserId, max_orders: OrderLimit) -> String {
format!("user {} limited to {} orders", user_id.0, max_orders.0)
}
fn main() {
let id = UserId(4000);
let cap = OrderLimit(5);
println!("{}", grant(cap, id)); // swapped
}
error[E0308]: arguments to this function are incorrect
|
| println!("{}", grant(cap, id));
| ^^^^^ --- -- expected `OrderLimit`, found `UserId`
| |
| expected `UserId`, found `OrderLimit`
Two structs, two lines, and the compiler names both sides of the mistake. This is the cheapest bet in the series and usually a good one, because a user id is not “some integer” — it is an identity, and identity deserves a type. But notice what made it work: there were two kinds of value. Where a value has no sibling to be confused with — a single counter, a loop index, a size — the newtype defends against a mistake nobody was going to make.
The boilerplate bill
The email is the other value in the signup flow, and here the case for a wrapper looks different. An email is a String with an invariant — it should contain an @, it should come from user input, and the rest of the code should not have to re-check it. The boundary post made the general case for validating at the edge; this is what one validated wrapper costs in full:
use std::fmt;
use std::str::FromStr;
pub struct Email(String);
#[derive(Debug)]
pub struct InvalidEmail;
impl fmt::Display for InvalidEmail {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid email")
}
}
impl std::error::Error for InvalidEmail {}
impl TryFrom<String> for Email {
type Error = InvalidEmail;
fn try_from(value: String) -> Result<Self, Self::Error> {
if value.contains('@') {
Ok(Email(value))
} else {
Err(InvalidEmail)
}
}
}
impl fmt::Display for Email {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromStr for Email {
type Err = InvalidEmail;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Email::try_from(s.to_owned())
}
}
Forty-one lines, counting the error type and its display, the conversion, and the string parsing, before the signup flow does anything with the email. That is the bill for one invariant — and it is worth paying exactly when the invariant is real. The test in try_from is deliberately weak (a real validator would be stricter), and the point survives either way: the wrapper converts “every function that touches an email must remember to check” into “the type cannot exist unvalidated”. When the invariant matters, forty-one lines buy the removal of a whole category of checks from the rest of the codebase.
When it does not matter, the same forty-one lines are the entire story. A theme: String the user picked from a list the server owns has no invariant worth a TryFrom; passing it through as a plain String — or a plain enum of known themes — is simpler and equally safe. The smart constructors post showed how to build the wrapper; this post’s question is whether to build it at all, and the answer is set by the invariant, not by fashion.
Markers have a ceiling
The escalation continues. User ids have scopes in this system — admin ids and guest ids must never be confused — and the typestate post showed how to put that distinction into the type with a marker parameter:
use std::marker::PhantomData;
struct Admin;
struct Guest;
struct Id<Scope> {
value: u64,
_scope: PhantomData<Scope>,
}
The bet pays where the confusion is real:
error[E0308]: mismatched types
|
| let _ = escalate(admin);
| -------- ^^^^^ expected `Id<Guest>`, found `Id<Admin>`
And it bills at every ordinary use site. A marker parameter must be named or inferred, and when inference runs out of information the compiler asks for help:
error[E0282]: type annotations needed for `Id<_>`
|
| let current = Id::new(1);
| ^^^^^^^ ---------- type must be known at this point
|
help: consider giving `current` an explicit type, where the type for type
parameter `Scope` is specified
|
17 | let current: Id<Scope> = Id::new(1);
| +++++++++++
The suggested fix names Id<Scope> — a type that does not exist at the call site. The compiler is correct and unhelpful at the same time, which is the marker tax in one message: every reader of this code now tracks a second axis (scopes), every signature carries the parameter, and compile errors mention types nobody wrote. The typestate post priced this axis for lifecycles — generic spread, one specialized copy per type, the storage problem. Those costs apply to any marker parameter, and the question to ask before adding one is the same question typestate asked about lifecycles: does this distinction have a real failure mode behind it? Cross-scope access is a security boundary, so here the answer can be yes. A distinction nobody has ever crossed wrong does not need a type; it needs a comment.
What the standard library wraps
The standard library is the closest thing to an answer key, because it has made this decision over and over across its public API. It wraps where an invariant or a niche exists, and leaves plain integers bare. NonZeroU32 exists because “not zero” is an invariant with consequences — division by zero, and a niche the layout post showed turning Option<NonZeroU32> into a free Option. Duration exists because a number without a unit is a bug in waiting. There is no std::PositiveF64 and no UserId - no invariant, no niche, no wrapper.
That pattern — wrap the values whose invariants the compiler can enforce or reward, pass the rest through — scales down to application code without modification. The standard library also shows the ceiling: it has no marker-parameterized identity types. There is no std::UserId with a scope parameter and no branded ids; the distinctions the standard library tracks publicly are plain enums and plain structs.
Criteria
The series’ tools are levers, and these questions set how far to pull each one.
Is there an invariant that outlives the function that creates the value? If no function can rely on the property being checked, no wrapper is needed; a plain String, u64, or struct is simpler and costs nothing. If yes, the wrapper pays — this is the email case.
Does the value cross a trust boundary? Input from users, files, network replies deserves validation, and a wrapper is how validation sticks — once the type exists, unvalidated values cannot reach the rest of the code. This is where the forty-one lines earn themselves.
Would mixing it up with another value of the same type produce a bug? The two-u64 swap shipped silently. If the domain has sibling values (an id and a count, a source and a destination port), one-line newtypes are the cheapest safety in the language. If a value has no siblings, the newtype protects against an impossible mistake.
Does the code path fix the value’s lifecycle? That is typestate’s question, and the typestate post gave the full answer: fixed sequences pay, event-driven ones take a runtime enum.
Who pays the conversion tax, and when? A wrapper inside one module can be added the day a bug appears — the change is internal, nothing breaks. A wrapper in a published API is a promise the public API post asked to be made deliberately: callers construct and pattern-match against the published shape, and adding a newtype later is a breaking change. So the plain decision can wait for evidence on internal types, but on public types it belongs to the design phase.
Where the series lands
Seven posts argued for putting knowledge into types: values that cannot exist in an invalid state, transitions the compiler checks, boundaries validated in one place. This post is the counterweight. Types should carry the invariants that matter — and only those. The skill this series has been building is telling the difference between a value the compiler can hold accountable and a value that is fine as a u64. The standard library has spent a decade making that call; application code makes it value by value, and the compiler reports — in errors like the ones quoted above — what each decision bought. If you have not read the earlier posts, the overview on modeling data with Rust’s type system is the starting point of the series.