Sub topic 3
A builder that enforces required fields
Assume Rust ownership, moves, generic types, traits, and basic Cargo use. A typestate builder stores its current state in a type parameter. The state is usually a zero-sized marker type, so it adds no runtime data.
Required fields as states
Missing and Present label whether the URL exists. The build method is implemented only for RequestBuilder<Present>.
use std::marker::PhantomData;
struct Missing;
struct Present;
struct Request {
url: String,
retries: u32,
}
struct RequestBuilder<S> {
url: Option<String>,
retries: u32,
_state: PhantomData<S>,
}
impl RequestBuilder<Missing> {
fn new() -> Self {
Self {
url: None,
retries: 0,
_state: PhantomData,
}
}
fn url(self, value: &str) -> RequestBuilder<Present> {
RequestBuilder {
url: Some(value.to_owned()),
retries: self.retries,
_state: PhantomData,
}
}
}
impl<S> RequestBuilder<S> {
fn retries(mut self, value: u32) -> Self {
self.retries = value;
self
}
}
impl RequestBuilder<Present> {
fn build(self) -> Request {
Request {
url: self.url.unwrap(),
retries: self.retries,
}
}
}
fn main() {
let request = RequestBuilder::new()
.retries(3)
.url("https://example.com")
.build();
println!("{} (retries: {})", request.url, request.retries);
}Sealing the state set
A sealed trait prevents users outside the module from inventing states. The public trait requires a private trait, and only the types you implement can satisfy that requirement.
mod sealed {
pub trait Sealed {}
}
trait State: sealed::Sealed {
const NAME: &'static str;
}
struct Missing;
struct Present;
impl sealed::Sealed for Missing {}
impl sealed::Sealed for Present {}
impl State for Missing {
const NAME: &'static str = "missing";
}
impl State for Present {
const NAME: &'static str = "present";
}Choosing a `PhantomData` form
PhantomData<T> tells Rust that a type logically owns or contains a T. It affects variance, drop checking, and automatic traits such as Send and Sync.
Use PhantomData<fn() -> T> when T is only a type tag and should not affect ownership or thread-safety properties. Other function-pointer forms express different variance. Choose the form that matches the real relationship, rather than using PhantomData<T> automatically.
>callout note > Marker types carry compile-time meaning. They do not need values, fields, or runtime checks.
Testing invalid transitions
Compile-fail doctests verify that forbidden calls remain forbidden:
let _request = RequestBuilder::new().build();
// error: no method named `build` foundWhen typestate is worth using
Typestate fits small, important protocols such as builders, locked resources, and network handshakes. It catches invalid call order before execution.
An enum with runtime checks is often better when states come from input, must be serialized, or change dynamically. Typestate can increase generic code, error-message size, and API complexity.
Exercise
Why does RequestBuilder::new().build() fail to compile?
Show answer
new returns RequestBuilder<Missing>, and build exists only for RequestBuilder<Present>.