Sub topic 9
A builder that enforces required fields
This chapter assumes you know ownership and moves, generic structs with impl blocks, and the marker types and PhantomData from the earlier chapters. You should also be able to read a Cargo compiler error.
The problem with ordinary builders
A common builder collects options and has a build() method. If a field is required, build() usually returns Result<T, Error> or panics when the field is missing. The mistake is caught at runtime, and every caller has to handle an error that a correct program never produces.
With typestate, the builder's type records which required fields have been set. build() exists only on the type where all of them are set. A missing field becomes a compile error, so build() can return the finished value directly.
Tracking one required field
Here the required field is url. The type parameter U is either Missing or Present.
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
}The code uses three kinds of impl block:
impl RequestBuilder<Missing>holdsnewandurl. Only a builder without a URL can start, and only it can set the URL.impl<U> RequestBuilder<U>holdsretries. This optional setter works in any state and returnsSelf, so the state is preserved.impl RequestBuilder<Present>holdsbuild. It exists only afterurlhas been called.
How the type changes
url takes self by value and returns a RequestBuilder<Present>. The old builder is moved, so it cannot be reused. The PhantomData<U> field is rebuilt with the new type argument, and it takes no memory.
The call order of retries and url does not matter. Both orders reach Present, so both compile.
The `expect` call
build calls expect on an Option. It cannot fail through the public API, because Present is only reachable through url, which always stores Some. The message documents that invariant.
Some designs avoid the Option altogether by storing a U-typed value in the field, with () for missing and String for present. That removes the expect but changes the type parameters, and each required field needs its own parameter. The marker approach keeps the field types simple.
Several required fields
Add one type parameter per required field, for example RequestBuilder<U, M> with a Missing or Present marker for each. Each setter then fixes one parameter and leaves the other generic, as in impl<M> RequestBuilder<Missing, M>. The final build lives in impl RequestBuilder<Present, Present>.
This costs more as fields grow. Two required fields give four combinations, and each setter needs its own impl block. For many required fields, consider whether a plain constructor taking them as arguments is simpler.
Reading the error
When you call build too early, the compiler reports that no method named build is found for RequestBuilder<Missing>. It also lists the type where the method does exist. This message is the tool for checking that the pattern works. A later chapter shows how to turn such failures into compile_fail doctests.
Exercise
Add a second required field, method: String, to the builder so that build() is available only after both url and method are set, in either order. How many type parameters does RequestBuilder need, and in which impl block does build go?
Show answer
Two marker parameters, for example RequestBuilder<U, M>, each Missing or Present. url goes in impl<M> RequestBuilder<Missing, M> and returns RequestBuilder<Present, M>. method goes in impl<U> RequestBuilder<U, Missing> and returns RequestBuilder<U, Present>. build goes in impl RequestBuilder<Present, Present>. new returns RequestBuilder<Missing, Missing>. Because each setter fixes only one parameter, the two can be called in any order.