Skip to content
Tutorials Center
My learning

Topics

Lesson 107 of 132 ยท Advanced Rust

Type System Techniques

Use Rust's type system to make bugs impossible - zero-sized types, unit newtypes, PhantomData, typestate, the never type, const evaluation and branded handles, with runnable code.

Most languages use types to describe data. Rust programmers also use types to describe rules: "this value is in meters", "this connection is already open", "this handle belongs to that arena". When a rule is part of a type, the compiler enforces it on every line of your program, and the check costs nothing at run time. The program that breaks the rule simply does not compile.

This lesson is a tour of the techniques that make that possible: zero-sized types, newtypes, PhantomData, typestate, the never type, compile-time evaluation and "branded" lifetimes. Each one is small. Together they are how libraries such as std, tokio and embedded-hal make misuse hard. You should know Generics, Traits and Lifetimes; the earlier lesson Typestate and Builders covers the builder side of this story in more detail.

Zero-sized types

A zero-sized type (ZST) is a type whose values carry no information, so they occupy no memory. The unit type (), an empty struct, an enum with one variant and PhantomData<T> are all zero-sized.

Rust Zero-sized types take no space

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Why would you want a type that holds nothing? Because a type is also a name. Two ZSTs with different names are different types, and the compiler treats them as such even though both are free. A HashSet<K> is built as a HashMap<K, ()>: the value type is a ZST, so the "map" stores only keys. A Result<T, Infallible> carries no error data. A unit struct implementing a trait is a strategy that costs nothing to pass around, as in BuildHasherDefault<H>.

Because ZSTs have no data, operations on them are optimized away completely. Vec<()> is just a counter, and an iterator over [(); N] compiles to a loop with no loads.

Newtypes: giving primitives a meaning

A newtype wraps one value in a one-field tuple struct. It has the same layout as the inner type but is a different type to the compiler, so you cannot mix them up by accident.

Rust Newtypes stop unit mix-ups (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler stops with error[E0308]: mismatched types, pointing at tower with the note expected Meters, found Feet``. With plain f64 parameters this call would compile and silently use a number in the wrong unit, the bug that famously lost a Mars orbiter. Now the fix is to convert explicitly, and the right place for that is a From implementation:

Rust Explicit, checked conversions between unit types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Newtypes also let you work around the orphan rule: you may not implement a foreign trait for a foreign type, but you can for your own wrapper. And they carry invariants: a struct Email(String) whose only constructor validates the text means that every Email anywhere in the program is already valid. The pattern is called "parse, don't validate": convert once at the edge, then pass the stronger type around.

PhantomData: a type parameter with no data

The newtype approach needs one struct per unit. If you have dozens of units, you want one generic struct with a marker type parameter instead. The problem: Rust rejects a type parameter that no field uses (error[E0392]: type parameter U is never used). PhantomData<U> is the standard answer. It is a ZST that tells the compiler "act as if this struct owned a U".

Rust One generic Quantity type for every unit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The struct is exactly 8 bytes: PhantomData adds nothing. Notice the hand-written Clone and Copy. #[derive(Clone)] on a generic struct adds the bound Unit: Clone, but Meters here does not implement Clone, so a derived impl would not apply. When the marker is only a label, write the impls yourself.

PhantomData has a second job: it controls variance and drop-checking. PhantomData<&'a T> makes a struct behave as if it held a reference, which is how you build a type that carries a lifetime without storing a reference, for example a raw-pointer-based iterator:

Rust
use std::marker::PhantomData;

struct RawIter<'a, T> {
    ptr: *const T,
    end: *const T,
    _borrow: PhantomData<&'a T>, // "this iterator borrows a slice of T for 'a"
}

Without the marker, the compiler would think RawIter borrows nothing and would let the slice be freed while the iterator is still alive. This is the point of the unsafe data structures lesson, where PhantomData<T> also tells the drop checker that the container owns its elements.

Typestate: the protocol in the type

The typestate pattern encodes the state of an object in its type. Methods that are legal only in some states exist only on that state's type, and transitions consume self and return the next state. Calling send on a closed connection is not a runtime error; the method does not exist.

Rust A connection whose methods depend on its state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Because open takes self by value, the old Closed connection is moved and cannot be used again. Ownership (Ownership) does the bookkeeping for free. Use typestate when misuse is likely and costly (hardware registers, protocol handshakes, file handles). Avoid it when states multiply or must be decided at run time (user input choosing the next state), where an enum is simpler.

The never type and uninhabited types

The type ! ("never") has no values. A function returning ! never returns: panic!, process::exit, loop {} and return all have type !, which is why they fit into any expression, such as the else branch of a let ... else. On stable Rust you can name ! only as a return type, but you can build your own uninhabited type with an enum that has no variants, and the standard library gives you one: std::convert::Infallible.

Rust Types with no values prove that something cannot happen

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Where does Infallible appear in practice? String: FromStr<Err = Infallible>, because every string can become a String. A generic function that accepts Result<T, E> can then be called with a type whose error can never happen, and the compiler lets you drop the error handling. Since Rust 1.82, a match on a Result<T, Infallible> may omit the Err arm, as shown in the example, because the empty pattern is unreachable.

Compile-time evaluation

Anything you can compute while compiling is a check you never need at run time. Three tools do this: const fn, const items and const { } blocks (inline const, stable since Rust 1.79), plus const assertions that turn a violated invariant into a compile error.

Rust Computing and asserting at compile time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Uncomment the last line and rustc reports error[E0080]: evaluation panicked: buffer size must be a power of two, and a note that the error was found while instantiating fn Buffer::<12>::new. The error appears at compile time, only for the instantiation that breaks the rule. This is how you put invariants on const generics that the type system cannot express directly. Limits: const fn cannot call trait methods (on stable), or allocate; read the compiler's message when it refuses.

Branded types: handles that belong to one owner

The last technique is the most advanced. Suppose an arena returns index handles. Nothing stops you passing a handle from arena A to arena B and reading the wrong item (or panicking). You can make the compiler tell the two arenas apart by giving each one a unique, invisible brand: a lifetime that no other arena can share.

Rust Handles that only work with their own arena

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Now try to smuggle a handle across arenas:

Rust A handle from the wrong arena is rejected (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The two arenas have different, unrelated 'id lifetimes, and because the brand is invariant, the compiler cannot unify them. The message is a lifetime error rather than a type error: error[E0521]: borrowed data escapes outside of closure, with the note that mutable references are invariant over their type parameter. This "generativity" trick appears in crates such as ghost-cell, indexing and qcell. It is rarely needed in application code, but understanding it deepens your grasp of variance and for<'a> bounds (Lifetime Patterns).

When to use these techniques, and when not

  • Newtypes: almost always worth it for IDs, units and validated strings. They cost nothing.
  • PhantomData markers: when you have many parallel types or need to carry a lifetime or ownership claim without data.
  • Typestate: when a protocol has a few states, misuse is costly and states are known at compile time.
  • Const checks: when an invariant depends only on constants or const generics.
  • Branding: only for library internals that need provable safety without runtime checks.

Avoid going further than the problem demands. Every extra type parameter appears in error messages and signatures, and a clever type that colleagues cannot read is a cost. A runtime check with a good error message is often the better engineering.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is std::mem::size_of::<PhantomData<String>>()?

    PhantomData<T> is a zero-sized type: it exists only for the type checker and occupies no memory.
  2. 2. Why does Quantity<Unit> implement Clone and Copy by hand instead of deriving them?

    #[derive] adds a bound on every type parameter. A marker used only as a label should not need to be Clone, so the manual impl has no such bound.
  3. 3. In the typestate example, why can send not be called on a Connection<Closed>?

    Methods that belong to one state live in an impl block for that state's type. Calling them on another state gives E0599: no method named ....
  4. 4. What does fn fail(msg: &str) -> ! tell the compiler?

    ! has no values; a call that produces it cannot complete, so it coerces to any type, for example in a match arm that must produce a u32.
  5. 5. What is the purpose of the invariant brand lifetime in Arena<'id, T>?

    Each call to with_arena creates a fresh, unrelated 'id. Invariance stops the compiler from unifying two of them, so a mixed-up handle is a compile error.

Summary

  • A type can encode a rule; the compiler checks the rule everywhere and it costs nothing at run time.
  • Zero-sized types ((), empty structs, PhantomData) carry no data but still give names to types.
  • Newtypes make units, IDs and validated values distinct; convert explicitly with From.
  • PhantomData<T> lets a generic struct mention a type or lifetime it does not store; write Clone/Copy by hand for marker parameters.
  • Typestate puts the protocol into the type: state-specific methods and self-consuming transitions.
  • ! and Infallible prove that a branch cannot happen.
  • const fn, inline const { } and assert! in associated consts move checks to compile time.
  • Branded (invariant) lifetimes tie a handle to the one owner that created it.

Next: Macros in Practice: DSLs