Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 132 ยท Generics

Type-State and Builder Patterns

Design Rust APIs that cannot be misused - the type-state pattern with PhantomData, owned and borrowed builders, compile-time required fields, sealed traits and generic API guidelines.

Most programs check their own rules while they run: "you can't read from a closed file", "an email needs a recipient", "don't send before connecting". When a rule is broken, the program panics or returns an error, and you find out in testing, or in production. Rust gives you another option. If you describe the rules with types, the compiler checks them before the program ever starts, and an invalid sequence of calls simply does not compile.

This lesson shows two related design patterns. The builder pattern makes objects with many options pleasant to create. The type-state pattern encodes "what state is this object in?" as a type parameter, so that only the methods valid for that state exist. Together with sealed traits and a few generic API habits, they are how well-designed libraries make mistakes hard. You will use generics, trait bounds and the zero-sized PhantomData from the previous lesson. Afterwards we move on to the collections chapter.

The problem: states checked at run time

Here is a door that can be open, closed or locked, written the usual way. A state field and a runtime check guard every action:

Rust State checked at run 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.

This works, but every method must remember to check, every caller must handle the Result, and the mistake on the lock line is only discovered by running the program. Can we make door.lock() on an open door a compile error? Yes, and the door will need less code.

The type-state pattern

The idea: make the state a type parameter. Door<Closed> and Door<Open> are two different types, and each gets only the methods that make sense for it. Transitions are methods that take self by value and return the door in its new state, which uses ownership in a clever way: once you call open, the old closed door is gone and cannot be used again.

Rust A door whose state is a type

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.

Read the impl blocks: open and lock are written inside impl Door<Closed>, so they exist only on closed doors. The generic impl<State> Door<State> holds what every state shares. The state costs no memory, since PhantomData is zero-sized: a Door is exactly the size of its String, 24 bytes.

Now the payoff. Trying an invalid transition is a compile error:

Rust Locking an open door (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 message is error[E0599]: no method named `lock` found for struct `Door<Open>` in the current scope. The compiler even adds that the method exists but only for Door<Closed>. A second mistake, using the old door after a transition, is caught by the move rules: after let open_door = door.open();, using door again reports error[E0382]: use of moved value: `door` .

Because transitions consume self, you can never accidentally keep using the stale value. This is the one thing a pure runtime state machine cannot give you.

Where type-state is used for real

  • Network and I/O protocols: a Connection<Disconnected> becomes Connection<Connected> after connect, and only the latter can send.
  • Hardware drivers in embedded Rust: a pin is Pin<Input> or Pin<Output>, and you cannot write to an input pin.
  • Builders that insist on mandatory fields (next section).
  • Transactions: Transaction<Open> can commit or rollback and then it is gone.

When not to use it

Type-state needs the state to be known at compile time. If the state comes from outside (a user's click, a network message, a database row), you must branch on it at run time, and an enum is the right tool. Also, a type-state API with many states can produce confusing error messages and many near-identical impl blocks. Use it for the small, important state machines where a mistake is costly.

The builder pattern

Rust has no named or default function arguments and no overloading. A struct with many optional settings is awkward to construct with Config::new(a, b, c, d, e, f). The builder pattern solves this: a second struct collects options through chainable methods, and a final build() produces the real thing, which is the right moment to validate.

Rust An owned builder with validation

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.

Four details to notice:

  • Setters take mut self and return Self, so calls chain and each call moves the builder along. This is the owned builder. It never needs clone and works well with temporaries.
  • impl Into<String> lets callers pass &str, String or anything convertible, without a manual .to_string(). See Display and From.
  • Defaults live in one place (ServerConfig::builder()). You could also derive Default.
  • build returns a Result, because some mistakes (a zero port) cannot be prevented by types alone.

Owned or borrowed builder?

There is a second style: setters take &mut self and return &mut Self. The standard library's std::process::Command and std::thread::Builder work this way. The difference matters when you want to configure a builder in a loop or in separate steps:

Rust A borrowed builder can be configured step by step

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 one-line QueryBuilder::new("users").filter(...) works because a temporary lives until the end of the statement. But storing the result of a chain in a variable, as in let b = QueryBuilder::new("x").filter("y");, would hold a reference to a temporary that has been dropped, and the borrow checker rejects it with error[E0716]: temporary value dropped while borrowed. With an owned builder that problem cannot occur. A good rule: owned builders for building a value that will be moved out (build(self)), borrowed builders when build can be called repeatedly or you want conditional configuration.

Mark builder methods with #[must_use]. If someone writes builder.port(80); with an owned builder, the new builder is silently thrown away and the setting is lost. With #[must_use] the compiler warns: "unused return value of port that must be used".

A builder that enforces required fields

A runtime Result is fine for validation rules. But "you must give an email a recipient and a subject" is a rule about which methods were called, and we can check that with types. Each required field gets a type parameter that is either Missing or Set<T>, and build() exists only when everything is Set:

Rust Required fields checked by the compiler

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 order of the calls does not matter (here subject comes before to) and the optional methods can appear anywhere. Forgetting a required step makes build disappear:

Rust Forgetting the subject (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 error is error[E0599]: no method named `build` found for struct `EmailBuilder<Set<String>, Missing>` in the current scope, and the note spells out the one impl block that has build: the one for EmailBuilder<Set<String>, Set<String>>. A real library would hide the long type names behind a public builder type, but the principle is the same.

The cost is code size: each required field adds a type parameter and impl blocks. Crates like bon and typed-builder generate this for you from a derive macro (they are third-party crates, so they cannot be run here). Use compile-time required fields for public libraries where a missing field is a plausible mistake; for small internal code a simple build() -> Result is usually enough.

Sealed traits

Look back at Door<State>. Anybody can write Door<Banana>, because State is an unconstrained type parameter. To restrict the allowed states we make a trait and bound the parameter by it. But if that trait is public, anyone can implement it for their own types too. A sealed trait is a public trait that nobody outside your crate can implement. The trick is to give it a supertrait living in a private module:

Rust A sealed State trait

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.

DoorState is public, but its supertrait Sealed lives in a module that other crates cannot name, so they cannot write impl sealed::Sealed for Banana, and therefore they cannot implement DoorState either. Because in this one-file demo everything is in the same crate, the lock is visible only if you imagine the code split into a library and an application. Sealing buys you the freedom to add methods or new states later without breaking anyone: in a normal library, adding a method to a public trait is a breaking change, unless the trait is sealed.

Generic API habits

A few conventions make generic APIs pleasant, and you have already met most of them:

  • Accept the general type, return the specific one. Take impl AsRef<str> or &str and return String; take &[T] instead of &Vec<T>.
  • Use impl Into<String> for owned text parameters, so callers need no .to_string().
  • Derive Default and let builders start from it.
  • Prefer impl Trait in arguments and returns for simple cases; use named generics (<T: Trait>) when the type appears more than once or callers need the turbofish.
  • Put bounds where they are needed. The Door<S: DoorState> struct bound is only worth it if the struct itself needs it; otherwise put the bound on the impl blocks.
  • Do not over-generalize. Every generic parameter makes error messages longer and compile times higher. If an API has only ever one implementation, a concrete type is simpler.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the type-state pattern, why do transition methods take self by value?

    Taking self by value moves the old state into the method. The caller receives the value in its new state and cannot touch the stale one.
  2. 2. What does PhantomData<State> cost at run time?

    PhantomData is zero-sized. It exists only for the compiler, so type-state adds no memory or speed cost.
  3. 3. A builder method is declared fn port(mut self, p: u16) -> Self. What kind of builder is it?

    Taking mut self and returning Self moves the builder through each call. A borrowed builder uses &mut self and returns &mut Self.
  4. 4. What makes a trait 'sealed'?

    There is no sealed keyword. The pattern relies on a public trait whose supertrait cannot be named, and therefore cannot be implemented, outside the crate.
  5. 5. When is an enum a better fit than type-state?

    Type-state needs the state at compile time. When the state arrives from outside the program you must branch at run time, and an enum models that directly.

Summary

  • Type-state encodes an object's state in a type parameter (Door<Open>). Methods live in impl blocks for specific states; transitions take self and return the new state.
  • PhantomData<S> stores the state tag at zero cost. Invalid call sequences become E0599 (no such method) or E0382 (use of moved value) at compile time.
  • Use enums instead when the state is only known at run time.
  • The builder pattern gives Rust named, optional and default arguments. Owned builders (mut self -> Self) suit one-shot construction; borrowed builders (&mut self -> &mut Self) suit step-by-step configuration.
  • Validate in build() -> Result; enforce mandatory fields in the type system with Missing and Set<T> parameters.
  • Sealed traits stop outside crates from implementing your trait, so you can evolve it safely.
  • Good generic APIs accept general types, return concrete ones, and avoid generics that have only one use.

Next: Vec