Newtype
A newtype is a tuple struct around an existing type, struct UserId(u64), so the compiler will not accept a raw u64 or a SessionId in its place.
Detailed Explanation
A type alias, type UserId = u64, is a new name for the same type. A newtype is a different type. fn lookup(id: UserId) will not take 42 or SessionId(42). That is the pattern: make illegal mixing unrepresentable.
The wrapper is free at runtime. UserId has the same layout as u64 (#[repr(transparent)] when you need that to be ABI-true). You add constructors that validate (UserId::parse), you keep the inner field private so callers cannot forge UserId(0), and you implement the traits you actually want (Display, FromStr, Serialize) instead of inheriting every u64 method.
Newtypes are also how you implement a foreign trait on a foreign type. The orphan rule blocks impl Serialize for chrono::DateTime. struct Stamp(chrono::DateTime<Utc>) plus impl Serialize for Stamp is legal because you own Stamp.
Do not newtype everything. A struct Meters(f64) is worth it if you have Feet in the same file. A struct Name(String) is worth it if an empty name is invalid and you want the constructor to be the only builder. A newtype around Vec<u8> that adds no invariant is noise.
When you reach for a newtype: ids, units, validated strings, orphan-rule wrappers. When you reach for a type alias: you only want a shorter name. When you reach for a full struct: you have more than one field.
Newtypes compose with Serde via #[serde(transparent)] so the wire format stays a number or a string while the Rust API stays typed. Skip that attribute and you serialise a single-element map or a tuple, which surprises every client. Decide the wire shape when you create the wrapper, not after the first mobile app ships.
Code Examples
struct UserId(u64);
struct SessionId(u64);
fn lookup(user: UserId) -> u64 {
user.0
}
fn main() {
println!("{}", lookup(UserId(17))); // prints: 17
// lookup(SessionId(17)); // does not compile
}Common Gotchas
A type alias does not give this safety
`type UserId = u64` still accepts any `u64`. Use a struct.
A public inner field can be forged
`UserId(pub u64)` lets anyone write `UserId(0)`. Keep it private if zero is invalid.
`Deref` to the inner type weakens the wrapper
Every inner method comes back. Prefer explicit `as_u64()` when the point is restriction.
`repr(transparent)` for FFI and some transmute cases
Without it, layout is usually the same but not a guarantee you should rely on at an ABI boundary.