I Stopped Passing Raw Strings and Integers Everywhere in Rust. Here Is What I Use Instead.
I wrote a function once that took three u64 arguments in a row, an account id, a destination id, and an amount in cents, and somewhere between writing it and calling it, two of those arguments traded places. The compiler said nothing. Every one of those three values was, as far as Rust was concerned, exactly the same kind of thing: an unsigned sixty-four-bit number, indistinguishable from its neighbors, perfectly willing to sit in any of the three slots I’d carved out for it. The bug wasn’t a typo. It was a design I’d built with my own hands, one that gave the compiler no way to help me even though it was, in every other corner of that same program, relentlessly picky about types.
The shape of the problem before it has a name
fn transfer(from: u64, to: u64, amount_cents: u64) {
// ...
}
transfer(destination_id, source_id, amount_cents); // compiles. wrong. silent.
fn transfer(from: u64, to: u64, amount_cents: u64) {
// ...
}
transfer(destination_id, source_id, amount_cents); // compiles. wrong. silent.
Every parameter here is a u64. The compiler checks that you’ve passed three numbers, in order, of the right width, and stops looking the moment that’s satisfied. It has no way to know that the first slot means “an account this money leaves” and the second means “an account this money arrives at,” because you never told it any such thing. You told it “a number,” three times, and it believed you exactly that much and not one grain more.
Java engineers have a name for this, worn smooth from decades of hitting it: primitive obsession. Passing raw Strings, longs, and ints everywhere instead of small, purpose-built types is one of the oldest, most repeated warnings in the language’s own literature, and the reason it keeps getting repeated is that the fix in Java is expensive enough that people quietly decide to live with the disease instead. A real wrapper class costs an object, a heap allocation, a constructor, boilerplate equals() and hashCode(), all to wrap a single long. Most teams weigh that cost, shrug, and keep passing longs.
The newtype pattern, and why Rust can afford it for free
struct AccountId(u64);
struct Cents(u64);
fn transfer(from: AccountId, to: AccountId, amount: Cents) {
// ...
}
struct AccountId(u64);
struct Cents(u64);
fn transfer(from: AccountId, to: AccountId, amount: Cents) {
// ...
}
A newtype is a struct with exactly one field, wrapping an existing type in a new name the compiler will now actually enforce. AccountId and Cents are both, underneath, nothing more than a u64. But they are no longer the same u64 as far as the type checker is concerned, and the moment you try to pass a Cents where an AccountId is expected, the compiler stops you cold, at the exact call site, before the program ever runs.
transfer(destination_id, source_id, amount);
transfer(destination_id, source_id, amount);
Worth being honest about that limitation before it undermines the whole argument: a newtype protects you from mixing up categories of value, Cents for AccountId, but it does not, on its own, stop you from swapping two arguments that are the same newtype in the same function signature, from: AccountId and to: AccountId are still interchangeable to the compiler, since both slots want an AccountId and both received one. The bug I opened with, three raw u64s tangled together, is fully solved the moment they become three distinct newtypes, AccountId, another AccountId, and Cents, because the amount can no longer wander into an id slot. Preventing the two id parameters from swapping with each other specifically needs a second technique, named arguments simulated through a small struct, or distinct newtypes per role (SourceAccountId, DestinationAccountId) if the distinction matters enough to enforce. The newtype pattern earns its keep by ruling out an entire category of mistake, not by ruling out every mistake in that neighborhood.
The part that makes this worth doing at all, the part Java simply cannot offer at the same price: this costs nothing at runtime. A struct with a single field has the exact same memory layout as the field itself, no extra pointer, no extra allocation, no boxing. AccountId occupies precisely as many bytes as the raw u64 it wraps, and the distinction between them exists entirely at compile time, evaporating completely by the time the program is actually running. You can make this guarantee explicit rather than merely conventional with #[repr(transparent)], which is worth reaching for specifically when the type crosses an FFI boundary and something on the other side needs to trust the layout matches exactly.
#[repr(transparent)]
struct AccountId(u64);
#[repr(transparent)]
struct AccountId(u64);
Getting the value back out, and giving the wrapper some manners
The raw value sits at field .0:
let id = AccountId(42);
println!("{}", id.0); // 42
let id = AccountId(42);
println!("{}", id.0); // 42
Reaching for .0 everywhere gets tedious fast, and it’s usually the first thing that makes a newtype feel like friction rather than a favor. The fix is to implement whichever traits actually make the wrapper pleasant to live with, borrowing directly from ground already covered in this series: Display so it prints cleanly, From/Into so it converts at the boundary without ceremony, and PartialOrd/Add when the underlying arithmetic genuinely still makes sense on the wrapped type.
fmt::Result {
write!(f, "{}", self.0)
}
}
impl From for AccountId {
fn from(value: u64) -> Self {
AccountId(value)
}
}
let id: AccountId = 42.into();
println!("{id}"); // no .0 needed here, Display handles it” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use std::fmt;
impl fmt::Display for AccountId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<u64> for AccountId {
fn from(value: u64) -> Self {
AccountId(value)
}
}
let id: AccountId = 42.into();
println!("{id}"); // no .0 needed here, Display handles it
use std::fmt;
impl fmt::Display for AccountId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<u64> for AccountId {
fn from(value: u64) -> Self {
AccountId(value)
}
}
let id: AccountId = 42.into();
println!("{id}"); // no .0 needed here, Display handles it
This is the same trait machinery from earlier in this series, just aimed at a much smaller, more deliberate target: instead of a whole custom type built for its own sake, you’re dressing a single wrapped primitive in exactly the behavior you want it to have, and refusing it every behavior you don’t. A Cents type, for instance, is a perfectly reasonable candidate for Add and Sub, since adding two amounts of money together still means something. It is not a reasonable candidate for Mul, since multiplying one amount of money by another amount of money produces a number with no sensible meaning, and simply never implementing that trait is how you make that nonsensical operation a compile error instead of a silent bug waiting for the day someone writes it by accident.
Where this earns its cost back the fastest
The accounts-and-cents example is the classic one, but the same fix pays off anywhere two values share a primitive type and nothing else: a UserId and a ProductId both happening to be u64, an Email and a Username both happening to be String, a Meters and a Seconds both happening to be f64. Every one of these pairs is a landmine sitting quietly in a function signature, waiting for the day two arguments get passed in the wrong order and nothing catches it, because nothing was ever asked to. Wrapping each in its own single-field struct turns “the compiler trusts you to remember” into “the compiler will not let you forget,” and the price for that insurance, in Rust specifically, rounds down to nothing.
If you’re curious how Java engineers have fought this exact battle for years without a free way to win it, that’s the whole premise of the book I’ve been writing: every classic data structure built once in Rust and once in Java, side by side, so you can see exactly where each language’s rules force a different decision. Ownership vs. Reference: Data Structures and Algorithms in Rust and Java
For the Rust foundations that series builds on: Zero to Rust: A Systems Programmer’s Field Guide — $7 · Free 20-page sample


