
Understand it
A newtype gives a bare value a meaning the type system can enforce, so a UserId cannot be passed where an OrderId belongs. A builder makes many optional parameters readable, and typestate encodes a protocol in types so calling a method in the wrong order simply does not compile.
Rust idioms use types and ownership to make intentions visible. A UserId newtype prevents accidentally passing an OrderId, even though both wrap u64. It is a zero-cost distinction in ordinary compiled code, but you still need explicit conversion at serialization and database boundaries. Option expresses absence; Result expresses failure with context. These enums make callers handle states that might otherwise be hidden in nulls or sentinel integers. Use pattern matching when it makes the state transition easier to read.
A builder is valuable when an object has several optional settings or validation before construction. Typestate goes further by representing stages as different types, so only a configured value exposes send(). Both patterns add API surface and can be overkill for a small internal helper. Start with a simple constructor; add richer types when misuse is likely or the workflow truly has stages. In the example, attempt load_user(OrderId(7)) and use the compiler error to explain the boundary. Then design a ParsedConfig that can become ValidatedConfig only after checking required fields. The goal is to encode stable domain rules, not to make every local variable into a wrapper. A good idiom reduces the amount of explanation needed at each call site.
Watch for type complexity that merely moves confusion. A builder with dozens of states can make an API harder to discover than a validated configuration struct. Show users a normal construction path in documentation, and keep error messages close to invalid input. Types are strongest when the domain invariant is stable and the compiler can give a clear failure at the call site.
Read the code
#[derive(Debug, Clone, Copy, PartialEq)]
struct UserId(u64);
#[derive(Debug, Clone, Copy, PartialEq)]
struct OrderId(u64);
fn load_user(id: UserId) -> String {
format!("user {}", id.0)
}
// load_user(OrderId(7)) won't compile.
println!("{}", load_user(UserId(7)));Two integers that can no longer be confused for each other.
Practice starter
fn transfer(from: u64, to: u64, amount: u64) { }
let (from, to, amount) = (1, 2, 30);
transfer(amount, from, to);Try it
Wrap a primitive in a newtype and pass it through one function.
What success looks like: Mixing it with another id of the same underlying type fails to compile.
Check your understanding
What does a newtype fix here?
Reveal the answer
- Nothing, the arguments are the same type
- Distinct types make a wrong argument order a compile error
- It removes a runtime check, so it is faster
Three bare u64s are interchangeable; AccountId and Amount are not.
Go deeper
Common misconception: “The compiler will catch swapped arguments, even when they are all u64.”
Three bare u64s are interchangeable, so the swapped call compiles. A newtype costs nothing at runtime and buys a real compile-time guarantee.
- Separate the ids:
UserIdandOrderIdboth wrap au64, but they are distinct types with no conversion between them. - Follow the call:
load_useraccepts only aUserId, andid.0reaches the inner value to formatuser 7. - Try the wrong id:
load_user(OrderId(7))fails with E0308, mismatched types, so the mistake never reaches runtime.
Transfer challenge: Rewrite the practice's transfer with AccountId and Amount newtypes. Predict how the swapped call now fails, then decide whether this API also needs a builder or typestate.
Connections
- Performance: Allocation, iterators, and measuring
- Macro Hygiene: Resolve generated names without accidental capture
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Rust Idioms (courseId "systems", lessonId "idioms") Link: https://crabrix.com/learn/systems/idioms/ Goal: A newtype costs nothing at runtime and buys a real compile-time guarantee. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=systems/idioms) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.