Sub topic 9
A Builder That Enforces Required Fields
This chapter assumes you know Rust ownership and moves, generic structs with impl blocks, and the basics of PhantomData and zero-sized marker types from earlier chapters. You should also be comfortable reading compiler errors. Here you will apply those pieces to a builder where build() does not exist until every required field has been set.
The problem with runtime-checked builders
A conventional builder stores every field as an Option and has build() return a Result. A caller who forgets a required field gets an Err at runtime, often far from the code that made the mistake. The compiler cannot help, because every builder has the same type no matter which fields it holds.
A typestate builder moves that check into the type system. Each required field gets a type parameter that is either Missing or Present. Setters change the parameter. build() is defined only in an impl block where all parameters are Present.
The working model
Three rules cover the whole pattern:
- One type parameter per required field. Optional fields need none.
- A setter for a required field takes
selfby value and returns the builder with that field's parameter set toPresent. build()lives in animplblock that names only the all-Presenttype.
The impl block for the starting type holds new(). Setters for optional fields sit in a block that is generic over every parameter, so they work in any state.
One required field
This builder requires url and treats retries as optional.
use std::marker::PhantomData;
struct Missing;
struct Present;
struct Request {
url: String,
retries: u32,
}
struct RequestBuilder<U> {
url: Option<String>,
retries: u32,
_url: PhantomData<U>,
}
impl RequestBuilder<Missing> {
fn new() -> Self {
RequestBuilder { url: None, retries: 0, _url: PhantomData }
}
fn url(self, url: &str) -> RequestBuilder<Present> {
RequestBuilder {
url: Some(url.to_string()),
retries: self.retries,
_url: PhantomData,
}
}
}
impl<U> RequestBuilder<U> {
fn retries(mut self, n: u32) -> Self {
self.retries = n;
self
}
}
impl RequestBuilder<Present> {
fn build(self) -> Request {
Request {
url: self.url.expect("url is set in the Present state"),
retries: self.retries,
}
}
}
fn main() {
let req = RequestBuilder::new()
.retries(3)
.url("https://example.com")
.build();
println!("{} (retries: {})", req.url, req.retries);
// RequestBuilder::new().build(); // error: no method named `build` found
}Three details matter here.
url()exists only onRequestBuilder<Missing>. It builds a new struct with a different type parameter. TheOption<String>field and theUparameter are separate: theOptionholds the data, andUrecords at compile time that the data was set.retries()is in the generic block, so it works before and afterurl(). The call order.retries(3).url(...)compiles.expectinbuild()cannot panic through safe use. The only way to reachRequestBuilder<Present>is throughurl(), which always storesSome. The message documents that invariant.
Two required fields
With more than one required field, each gets its own parameter. This example requires host and port, and timeout_secs is optional.
use std::marker::PhantomData;
struct Missing;
struct Present;
#[derive(Debug)]
struct Connection {
host: String,
port: u16,
timeout_secs: u32,
}
struct ConnectionBuilder<H, P> {
host: Option<String>,
port: Option<u16>,
timeout_secs: u32,
_state: PhantomData<(H, P)>,
}
impl ConnectionBuilder<Missing, Missing> {
fn new() -> Self {
ConnectionBuilder {
host: None,
port: None,
timeout_secs: 30,
_state: PhantomData,
}
}
}
impl<H, P> ConnectionBuilder<H, P> {
fn host(self, host: &str) -> ConnectionBuilder<Present, P> {
ConnectionBuilder {
host: Some(host.to_string()),
port: self.port,
timeout_secs: self.timeout_secs,
_state: PhantomData,
}
}
fn port(self, port: u16) -> ConnectionBuilder<H, Present> {
ConnectionBuilder {
host: self.host,
port: Some(port),
timeout_secs: self.timeout_secs,
_state: PhantomData,
}
}
fn timeout_secs(mut self, secs: u32) -> Self {
self.timeout_secs = secs;
self
}
}
impl ConnectionBuilder<Present, Present> {
fn build(self) -> Connection {
Connection {
host: self.host.expect("host is set in the Present state"),
port: self.port.expect("port is set in the Present state"),
timeout_secs: self.timeout_secs,
}
}
}
fn main() {
let conn = ConnectionBuilder::new()
.port(5432)
.timeout_secs(10)
.host("db.internal")
.build();
println!("{:?}", conn);
}The setters carry the other parameter through unchanged. host() turns <H, P> into <Present, P>, so it works whether or not the port is already set. The setters can run in either order.
With N required fields the builder has 2^N possible states. You do not write 2^N impl blocks. The generic setters cover all of them, and only build() needs a concrete block.
Storing the value in the state type
The Option plus expect in the examples above is a small blemish. If the state type holds the value, the compiler enforces presence and no Option is needed. The type parameters are then used by fields, so PhantomData is not required.
struct Missing;
struct Set<T>(T);
#[derive(Debug)]
struct Connection {
host: String,
port: u16,
timeout_secs: u32,
}
struct Builder<H, P> {
host: H,
port: P,
timeout_secs: u32,
}
impl Builder<Missing, Missing> {
fn new() -> Self {
Builder { host: Missing, port: Missing, timeout_secs: 30 }
}
}
impl<H, P> Builder<H, P> {
fn host(self, host: impl Into<String>) -> Builder<Set<String>, P> {
Builder {
host: Set(host.into()),
port: self.port,
timeout_secs: self.timeout_secs,
}
}
fn port(self, port: u16) -> Builder<H, Set<u16>> {
Builder {
host: self.host,
port: Set(port),
timeout_secs: self.timeout_secs,
}
}
fn timeout_secs(mut self, secs: u32) -> Self {
self.timeout_secs = secs;
self
}
}
impl Builder<Set<String>, Set<u16>> {
fn build(self) -> Connection {
Connection {
host: self.host.0,
port: self.port.0,
timeout_secs: self.timeout_secs,
}
}
}
fn main() {
let conn = Builder::new().host("db.internal").port(5432).build();
println!("{:?}", conn);
}This version has no panic path. The cost is that Missing is no longer zero-sized in spirit only: Set<String> holds real data, so the builder's size depends on its state. That is fine for a builder. Use the PhantomData form when the state types must stay pure tags, as in the sealed State trait from the previous chapter.
Common errors
Calling build() too early. The compiler reports something like this:
error[E0599]: no method named `build` found for struct `ConnectionBuilder<Present, Missing>` in the current scope
= note: the method was found for `ConnectionBuilder<Present, Present>`Read the type in the message. It names the field you forgot, which is the pattern's main benefit. The message is a type error and does not say "port is required", so document required fields in the builder's rustdoc.
Type inference failure on new(). If you place new() in the generic block, ConnectionBuilder::new() cannot infer H and P, and you get error E0282 (type annotations needed). Keep new() in the impl block for the all-Missing type.
Using the builder after a setter. Setters take self by value, so this fails with a use-of-moved-value error:
let b = ConnectionBuilder::new();
let b2 = b.host("a");
let b3 = b.port(1); // error[E0382]: use of moved value: `b`Rebind with let b = b.host("a"); or chain the calls.
Conditional setters. This does not compile, because the two branches have different types:
let mut b = ConnectionBuilder::new();
if use_tls {
b = b.host("secure.internal"); // error[E0308]: mismatched types
}A setter changes the type, so it cannot be assigned back to the same variable. Shadow the binding in each branch, or compute the value first and call the setter once. When the choice is unconditional you can write b.host(if use_tls { "secure.internal" } else { "plain.internal" }).
Forgetting mut self. A setter that returns Self and changes a field needs mut self. A setter that changes the type constructs a new struct and needs only self.
Trade-offs
| Concern | Runtime `Result` builder | Typestate builder |
|---|---|---|
| Missing required field | `Err` at runtime | Compile error |
| Error message quality | Custom text you write | Type-mismatch text from the compiler |
| Setting fields conditionally | Easy | Needs shadowing or restructuring |
| Storing the builder in a struct field | One simple type | Type must name every parameter |
| Setters called from data-driven code (config files, user input) | Natural | Awkward, because the call order is fixed in source |
| Code to write | Small | One parameter per required field |
Use a typestate builder when the caller is Rust code that knows at the call site which fields it sets. That covers library APIs where a forgotten field is a likely bug. Avoid it when the values come from data you only learn at runtime, or when the builder has more than three or four required fields. In those cases a plain constructor that takes the required values as arguments, with a builder for the optional ones, is simpler and gives clearer errors.
Exercise
In the two-field builder, you add fn verbose(mut self, on: bool) -> Self to the impl<H, P> ConnectionBuilder<H, P> block. Is a call such as ConnectionBuilder::new().verbose(true).host("h").port(1).build() valid? What happens if you move verbose into impl ConnectionBuilder<Present, Present> instead?
Show answer
The call is valid. verbose is generic over H and P, so it works in the Missing + Missing state and returns the same type, and the later setters then move the builder to Present + Present. If you move verbose into the Present, Present block, the call fails to compile, because verbose is called on ConnectionBuilder<Missing, Missing> and no such method exists for that type. The call would be valid only after both required fields were set.
Exercise
Add a required database: String field to the Set<T> version of the builder. What changes in the struct, in the setters, and in build()?
Show answer
Add a third parameter D and a field database: D to Builder<H, P, D>. new() returns Builder<Missing, Missing, Missing>. A new database setter returns Builder<H, P, Set<String>>. The existing host, port and timeout_secs setters must now carry D through: they become generic over <H, P, D> and return Builder<Set<String>, P, D>, Builder<H, Set<u16>, D> and Self. build() moves to impl Builder<Set<String>, Set<u16>, Set<String>> and reads self.database.0.