In a Rust typestate HTTP request builder, how do you make calling `send()` before setting a URL a compile error instead of a runtime check?
answer
- state as a type parameter
- impl block per state
- transition consumes self
- E0599, then E0382
basics
~10 sMake the state a type parameter: url(self, ...) consumes a RequestBuilder<NoUrl> and returns a RequestBuilder<HasUrl>, and send is defined only in impl RequestBuilder<HasUrl>. An early send is E0599; reusing the consumed builder is E0382.
solid answer
~40 sEncode the state in the type: `struct RequestBuilder<S> { url: Option<String>, headers: ..., _state: PhantomData<S> }` with zero-sized `NoUrl` and `HasUrl` markers. `impl RequestBuilder<NoUrl>` holds `new` and `url(self, url: &str) -> RequestBuilder<HasUrl>`; `impl RequestBuilder<HasUrl>` holds `send(self)`; methods valid in every state go in `impl<S> RequestBuilder<S>`. Calling `send` on a `RequestBuilder<NoUrl>` fails with E0599, "no method named `send` found", and rustc notes it exists for `RequestBuilder<HasUrl>`. Transitions take `self` by value, so the old-state builder is moved and cannot be used again (E0382). The cost is that the state must be known statically: both branches of an `if` must produce the same state type.
code
rust · 43 linesuse std::marker::PhantomData;
struct NoUrl;
struct HasUrl;
struct RequestBuilder<S> {
url: Option<String>,
headers: Vec<(String, String)>,
_state: PhantomData<S>,
}
impl RequestBuilder<NoUrl> {
fn new() -> Self {
RequestBuilder { url: None, headers: Vec::new(), _state: PhantomData }
}
fn url(self, url: &str) -> RequestBuilder<HasUrl> {
RequestBuilder { url: Some(url.to_owned()), headers: self.headers, _state: PhantomData }
}
}
impl<S> RequestBuilder<S> {
fn header(mut self, name: &str, value: &str) -> Self {
self.headers.push((name.to_owned(), value.to_owned()));
self
}
}
impl RequestBuilder<HasUrl> {
fn send(self) -> String {
let url = self.url.expect("the HasUrl state is only reachable through url()");
format!("GET {url} with {} header(s)", self.headers.len())
}
}
fn main() {
let reply = RequestBuilder::new()
.header("accept", "application/json")
.url("https://example.com/items")
.send();
println!("{reply}");
println!("{} {}", size_of::<RequestBuilder<NoUrl>>(), size_of::<RequestBuilder<HasUrl>>());
println!("{} {}", size_of::<NoUrl>(), size_of::<PhantomData<HasUrl>>());
}go deeper
Recall that a method defined only in impl RequestBuilder<HasUrl> simply does not exist on RequestBuilder<NoUrl>.
Explain the three impl blocks, why transitions take self by value, and what E0599 and E0382 mean in this pattern.
Judge when typestate beats a runtime check: fixed order and costly misuse, not run-time state, mixed collections or many independent requirements.
Decide where a public API offers typestate and where it offers a checked runtime path, and how the two convert into each other.
## The idea: states as types A conventional builder keeps a field such as `url: Option<String>` and checks it in `send`, returning an error or panicking when it is `None`. A **typestate** builder moves that check into the type system: each state is a distinct type, and a method exists only on the types where calling it is valid. Misuse is a compile error instead of a runtime failure. ## Building it step by step 1. **Define zero-sized state markers**: `struct NoUrl;` and `struct HasUrl;`. 2. **Make the builder generic over the state**: `struct RequestBuilder<S> { url: Option<String>, headers: Vec<(String, String)>, _state: PhantomData<S> }`. The `PhantomData<S>` field uses `S` without storing anything. 3. **Put each method in the impl block for the states that allow it**: - `impl RequestBuilder<NoUrl>` holds `new()` and `url(self, url: &str) -> RequestBuilder<HasUrl>`. - `impl RequestBuilder<HasUrl>` holds `send(self)`. - `impl<S> RequestBuilder<S>` holds `header(self, ...) -> Self`, which works in every state and keeps that state. 4. **Make each transition consume `self`** and build the new-state struct from the old fields. A chain such as `RequestBuilder::new().header("accept", "application/json").url("https://example.com/items").send()` type-checks step by step: `new` gives `RequestBuilder<NoUrl>`, `header` keeps it, `url` produces `RequestBuilder<HasUrl>`, and only then does `send` exist. ## What the compiler reports | Mistake | What rustc 1.99 says | |---|---| | `send()` before `url()` | E0599, "no method named `send` found for struct `RequestBuilder<NoUrl>`", with the note "the method was found for `RequestBuilder<HasUrl>`" | | Using the builder again after `url()` moved it | E0382, "use of moved value", noting that `url` "takes ownership of the receiver `self`" | | Choosing the state at run time, `if ok { b.url(u) } else { RequestBuilder::new() }` | E0308, "`if` and `else` have incompatible types" | The E0599 note is the payoff: the error names the missing step. ## Why transitions take self by value A method's receiver decides what happens to the old value. `&mut self` cannot change the type of the value it points to: a `RequestBuilder<NoUrl>` behind a mutable reference stays a `RequestBuilder<NoUrl>`. Returning a new `RequestBuilder<HasUrl>` from `&self` would compile if it cloned the fields, but the caller would still hold the old `NoUrl` builder and could keep using it. Taking `self` by value **moves** the old builder into the method, so after `let ready = draft.url(...)`, any use of `draft` is E0382. The type system then guarantees each builder value is in exactly one state. ## What it costs - **Run-time cost: none.** The markers and `PhantomData` are zero-sized, so every state has the same layout, and a transition moves the same fields. - **The state must be static.** Each branch of an `if` or `match` has to produce the same type, so a state decided by run-time input needs an enum wrapper or a runtime-checked API next to the typestate one. - **No mixed collections.** A `Vec` holds one element type, so builders in different states cannot share one without an enum. - **Combinatorial growth.** Two independent requirements, such as URL and method, need either four state combinations or two type parameters, which makes signatures noisy. - **Leftover runtime representation.** With `PhantomData` markers, `send` still unwraps an `Option` that the type guarantees is `Some`. Letting the state carry the data, `struct HasUrl(String)` stored as `state: S`, removes that. ## When typestate is worth it Typestate pays off when misuse is costly and the order is fixed: a connection that must be authenticated before queries, a hardware peripheral that must be configured before use, a transaction that must be signed before it is submitted. For a builder with many optional fields and one simple rule, a runtime check returning `Result` is often clearer. The test is whether callers write the sequence in straight-line code; if the state depends on input, the type-level version fights them. Typestate is also not the same as an enum of states. An enum makes illegal *values* unrepresentable and is matched at run time; typestate makes illegal *calls* impossible to write and is resolved entirely during type checking.
- How do you offer this builder when the URL may come from optional configuration at run time?Keep the typestate path for straight-line code and add a runtime entry point, for example a function returning `Result<RequestBuilder<HasUrl>, MissingUrl>` that checks the `Option` once. After that conversion the rest of the code is statically checked again.
- How do you share a `timeout` setter across all states without writing it twice?Put it in a generic impl, `impl<S> RequestBuilder<S> { fn timeout(mut self, d: Duration) -> Self { ...; self } }`. It returns `Self`, so the state type is preserved and the chain can continue in whatever state it was in.
- Could a `const` bool parameter replace the marker types?Yes for two states: `struct Request<const HAS_URL: bool>` with `impl Request<false>` and `impl Request<true>` behaves the same, and the early-send error is still E0599. Named marker types read better in errors and scale past two states.
It works like an airport where only the check-in desk prints boarding passes: the gate never asks whether you checked in, because without check-in you have no boarding pass to show, and the gate only accepts boarding passes.
- Typestate still needs a runtime state field that send checks
- A &mut self method can move the builder into its next state
- Builders in different states can be kept together in one Vec
- Calling send too early panics in debug builds and is ignored in release
- Typestate adds a tag field per state, so it costs memory