In a Rust library's typestate builder, why seal the `State` trait that bounds `RequestBuilder<S: State>`, and how does the sealing work?
answer
- closed set of states
- supertrait nobody else can name
- pub trait inside a private module
- E0277 downstream
basics
~20 sGive State a supertrait declared pub inside a private module and implement it only for NoUrl and HasUrl. Other crates can still use State in bounds but cannot implement it (E0277), so the builder's set of states stays closed.
solid answer
~40 sWith `pub struct RequestBuilder<S: State>`, the bound already stops nonsense like `RequestBuilder<String>`, but an unsealed public `State` lets any crate add `impl State for Sent {}` and name `RequestBuilder<Sent>` in generic code the library never designed for. Sealing closes that: `mod private { pub trait Sealed {} }`, then `pub trait State: private::Sealed {}`, with `Sealed` implemented only for `NoUrl` and `HasUrl`. Downstream, `impl http::State for Sent {}` fails with E0277, "the trait bound `Sent: http::private::Sealed` is not satisfied", and implementing `Sealed` directly hits E0603, "module `private` is private". Callers can still write `fn f<S: http::State>(...)`. Sealing does not control construction; private fields do.
code
rust · 31 linesuse std::marker::PhantomData;
mod private {
pub trait Sealed {}
}
pub trait State: private::Sealed {}
pub struct NoUrl;
pub struct HasUrl;
impl private::Sealed for NoUrl {}
impl private::Sealed for HasUrl {}
impl State for NoUrl {}
impl State for HasUrl {}
pub struct RequestBuilder<S: State> {
url: Option<String>,
_state: PhantomData<S>,
}
impl RequestBuilder<NoUrl> {
pub fn new() -> Self { RequestBuilder { url: None, _state: PhantomData } }
pub fn url(self, url: &str) -> RequestBuilder<HasUrl> {
RequestBuilder { url: Some(url.to_owned()), _state: PhantomData }
}
}
impl RequestBuilder<HasUrl> {
pub fn send(self) -> String { format!("GET {}", self.url.unwrap_or_default()) }
}go deeper
Recall that a sealed trait can be used by other crates but only implemented by the crate that defines it.
Explain the private-module supertrait, and why downstream impls fail with E0277 and direct Sealed impls with E0603.
Separate what sealing guarantees, a closed set of states, from what private fields guarantee, controlled construction, and design both into a typestate API.
Decide which public traits in a library should be sealed from the start, since unsealing later is easy and sealing later breaks users.
## Why a typestate library bounds its states A typestate builder in a library usually starts with a trait that names the valid states: ```rust use std::marker::PhantomData; pub trait State {} pub struct NoUrl; pub struct HasUrl; impl State for NoUrl {} impl State for HasUrl {} pub struct RequestBuilder<S: State> { url: Option<String>, _state: PhantomData<S>, } ``` The bound `S: State` already rejects `RequestBuilder<String>` with **E0277**, "the trait bound `String: State` is not satisfied". It also lets the library write generic code over states, such as `impl<S: State> RequestBuilder<S>` for setters that work everywhere, or a `Debug` impl that prints the state's name through a trait method. All of that is written assuming the states are exactly `NoUrl` and `HasUrl`. ## What goes wrong when State is open `State` is public, so any downstream crate may implement it for its own type. The orphan rule allows `impl http::State for Sent {}` because `Sent` is local to that crate. After that: - `RequestBuilder<Sent>` becomes a nameable type, and the library's generic `impl<S: State>` methods claim to apply to it. - Generic code in other crates, `fn log<S: http::State>(b: &RequestBuilder<S>)`, has to consider states the library never designed. - Adding a required method to `State` later breaks every downstream impl. This SemVer side of sealing is covered with API evolution. None of this makes the builder unsound, but the type-level guarantee the pattern exists for, "the builder is in one of these states", is no longer something the library controls. ## How the sealing works The **sealed trait pattern**, described in the Rust API Guidelines as C-SEALED, relies on visibility: 1. Declare a private module: `mod private { pub trait Sealed {} }`. `Sealed` is `pub`, but its module is not, so code outside the crate cannot name it. 2. Make it a supertrait: `pub trait State: private::Sealed {}`. Implementing `State` for a type requires that type to implement `Sealed` too. 3. Implement `Sealed` only for the library's own state types: `impl private::Sealed for NoUrl {}` and `impl private::Sealed for HasUrl {}`. Because `Sealed` lives in a private module, rustc does not complain about a private trait in a public interface; the trait itself is `pub`, it is merely unreachable. ## What downstream code sees | Downstream code | Result with rustc 1.99 | |---|---| | `impl http::State for Sent {}` | E0277, "the trait bound `Sent: http::private::Sealed` is not satisfied", listing `NoUrl` and `HasUrl` as the implementors | | `impl http::private::Sealed for Sent {}` | E0603, "module `private` is private" | | `fn describe<S: http::State>(b: &http::RequestBuilder<S>)` | compiles: the trait can be used in bounds | | `http::RequestBuilder<String>` | E0277 from the struct's `S: State` bound | Sealing restricts who can **implement** the trait, not who can **use** it. Document that the trait is sealed, as the guidelines advise, so users do not waste time trying to implement it. ## What sealing does not do - **It does not control construction.** Whether outside code can produce a `RequestBuilder<HasUrl>` without calling `url()` depends on the struct's fields being private and on there being no public constructor for that state. Privacy is covered with visibility; sealing only closes the set of states. - **It is not `#[non_exhaustive]`.** That attribute applies to structs, enums and enum variants; on a trait rustc rejects it with "the `non_exhaustive` attribute cannot be used on traits". - **It is not `unsafe trait`.** An unsafe trait can still be implemented downstream with `unsafe impl`; it only makes the implementer promise something. - **It does not freeze the trait entirely.** Removing or changing a public method of a sealed trait is still a breaking change. ## Is it worth doing? For a typestate API inside one crate, sealing adds little: nothing outside can implement the trait anyway if it is not public. It matters when the builder, its states and the `State` trait are all exported, which is the normal case for a library such as an HTTP client or a hardware driver crate. There, three small declarations keep the state machine the library documented the only one that exists.
- Can a downstream crate still write functions generic over the sealed `State`?Yes. Sealing only blocks implementations. `fn describe<S: http::State>(b: &http::RequestBuilder<S>)` compiles in another crate and accepts builders in either state, because using a trait in a bound never requires naming its supertrait.
- Why does `impl http::State for Sent {}` not trip the orphan rule instead?The orphan rule allows an impl when the trait or the type is local, and `Sent` is local to the downstream crate. The impl is allowed in principle and fails only because `Sent` lacks the `Sealed` supertrait, which is E0277.
- Putting #[non_exhaustive] on a trait stops other crates implementing it
- Sealing State on its own stops outside code constructing a builder in any state
- A sealed trait cannot be named in downstream bounds such as S: http::State
- An unsafe trait can only be implemented inside its own crate
- Implementing a foreign trait for a local type breaks the orphan rule