Sub topic 10
Closing the set of states with a sealed trait
This chapter assumes you know Rust generics and trait bounds, impl blocks, and the state types (Open, Closed) and PhantomData field from the earlier typestate chapters. Here you close the set of valid states so that nobody can add to it by accident or on purpose.
The set of states is open by default
The Door<S> types so far accept any S. Nothing says the parameter must be a state. If the struct is generic and unbounded, these both compile:
use std::marker::PhantomData;
struct Door<S> {
_state: PhantomData<S>,
}
fn main() {
let _nonsense: Door<String> = Door { _state: PhantomData };
let _also: Door<Vec<i32>> = Door { _state: PhantomData };
println!("compiles");
}Door<String> has no methods, because the impl blocks target Door<Open> and Door<Closed>. It is still a valid type, and it shows up in signatures, error messages and documentation. A reader cannot tell from the type definition which parameters are meant to be states.
Step one: a State trait
The first fix is to name the idea with a trait and bound the parameter by it:
pub trait State {}
pub struct Open;
pub struct Closed;
impl State for Open {}
impl State for Closed {}With struct Door<S: State>, the type Door<String> no longer compiles. The trait can also carry data for each state, such as a const NAME: &'static str, which you can read as S::NAME in code that is generic over the state.
This only partly solves the problem, because traits are open. Any other crate that depends on yours can write impl State for Paused {} and get a Door<Paused>. If your docs say "a door is open or closed" and your code assumes it, that downstream impl breaks your assumption. It also stops you from making changes later. If you add a required item to State, you break every downstream implementation.
Step two: seal the trait
A sealed trait is a public trait that only your crate can implement. The standard recipe has three parts:
- Create a private module that holds a public marker trait, usually called
Sealed. - Make the public trait require
Sealedas a supertrait. - Implement
Sealedfor your state types, then implement the public trait for them.
A downstream crate that wants to implement State must also implement Sealed. It cannot name Sealed, because the module that contains it is private. The rule "outside code cannot write this impl" comes from ordinary privacy.
The example below puts everything in a door module and uses main as the outside code. Module privacy works at the module boundary, so this simulates a downstream crate and still runs as one file.
mod door {
use std::marker::PhantomData;
mod sealed {
pub trait Sealed {}
}
pub trait State: sealed::Sealed {
const NAME: &'static str;
}
pub struct Open;
pub struct Closed;
impl sealed::Sealed for Open {}
impl sealed::Sealed for Closed {}
impl State for Open {
const NAME: &'static str = "open";
}
impl State for Closed {
const NAME: &'static str = "closed";
}
pub struct Door<S: State> {
name: String,
_state: PhantomData<S>,
}
impl<S: State> Door<S> {
pub fn describe(&self) -> String {
format!("{} is {}", self.name, S::NAME)
}
}
impl Door<Closed> {
pub fn new(name: &str) -> Self {
Door { name: name.to_string(), _state: PhantomData }
}
pub fn open(self) -> Door<Open> {
Door { name: self.name, _state: PhantomData }
}
}
impl Door<Open> {
pub fn close(self) -> Door<Closed> {
Door { name: self.name, _state: PhantomData }
}
}
}
use door::{Closed, Door};
fn show<S: door::State>(door: &Door<S>) {
println!("{}", door.describe());
}
fn main() {
let door: Door<Closed> = Door::new("front");
show(&door);
let door = door.open();
show(&door);
let door = door.close();
show(&door);
// Outside code cannot add a state:
//
// struct Paused;
// impl door::State for Paused {
// const NAME: &'static str = "paused";
// }
// error[E0277]: the trait bound `Paused: Sealed` is not satisfied
//
// impl door::sealed::Sealed for Paused {}
// error[E0603]: module `sealed` is private
}Running it prints:
front is closed
front is open
front is closedThe generic function show works with any state, because outside code can still use State as a bound. Sealing blocks implementing the trait. Using it is still allowed.
How the pieces fit
The compiler checks the supertrait relationship. impl State for Paused requires Paused: Sealed. Only code inside the door module can write impl Sealed for Paused, so the set of implementors is closed.
Why a pub trait in a private module
It looks odd to mark Sealed as pub and then hide it. There is a reason. State is public, and a public trait's supertraits must be at least as visible as the trait. If Sealed were pub(crate) or private, current compilers warn through the private_bounds lint, and older versions reject the code outright. Marking Sealed as pub satisfies that rule. Putting it in a private module makes it unnameable, which is what gives you the seal.
Two details matter for this to hold:
- The module
sealedmust not bepub, and you must not writepub use sealed::Sealedanywhere. A re-export undoes the seal. - Implement
Sealedonly for the types you own. Never write a blanketimpl<T> Sealed for T, which would make every type satisfy the supertrait and reopen the set.
What sealing buys you
| Benefit | Explanation |
|---|---|
| Closed set of states | Types such as `Door<String>` or `Door<Paused>` cannot exist. Code that is generic over `S: State` only has to consider the states you ship. |
| Safe evolution | Adding a method or associated const to `State` cannot break downstream code, because nobody else implements it. |
| Safe blanket impls | You can add `impl<S: State> Display for Door<S>` and know that no downstream type can conflict with it. |
| Per-state data | Associated consts and methods on `State` hold data such as `NAME`, so generic code can read them without matching on a value. |
Adding a new state is also non-breaking for downstream users in most cases. Their code can use S: State as a bound but cannot have implemented it, so a new implementor cannot invalidate anything they wrote.
Where to put the bound
You have two choices for where S: State appears:
- On the struct:
struct Door<S: State>. The type cannot be named with a non-state, and error messages are clearer. Everyimpl<S: State>block must repeat the bound, which is a small cost. - Only on impl blocks:
struct Door<S>plusimpl<S: State> Door<S>.Door<String>can be named but is useless, because no methods or constructors exist for it.
For a public API, the bound on the struct is usually better. It documents intent at the point of definition, and it makes the type signature itself say that S must be a state. Be aware that derive macros such as #[derive(Clone)] add S: Clone to the generated impl. Marker types then need Clone too, or you must write the impl by hand.
Alternatives to the supertrait approach
| Approach | How it seals | Notes |
|---|---|---|
| Private supertrait | `trait State: sealed::Sealed` | The standard recipe. Clear error messages. |
| Private method type | A trait method takes an argument of a private type, which downstream code cannot name. | Works, but the errors are harder to read. |
| `enum` instead of types | States are variants, not types. | Gives up compile-time method availability. See the trade-offs chapter. |
| Documentation only | "Do not implement this." | No enforcement. |
The supertrait approach is the most common in the ecosystem, so readers will recognise it.
Common mistakes
- Making
sealedpublic by accident. Apub mod sealedis a seal with a hole. Check the visibility when you move code around. - Forgetting the
Sealedimpl for a new state. The compiler reportsthe trait bound X: Sealed is not satisfiedon your ownimpl State for X. Addimpl sealed::Sealed for X {}. - Sealing too early. If you want users to define their own states, such as plugin systems, an open trait is correct. Seal only when the set of states is part of your design.
- Expecting exhaustiveness. A sealed trait gives you a closed set but no
match. You cannot ask the compiler to check that you handled every state, as you could with an enum.
Exercise
Why must the Sealed trait be declared pub even though it lives in a private module, and what would break if you removed the pub?
Show answer
State is a public trait, and its supertrait must be at least as visible as the trait itself. A private Sealed triggers the private_bounds lint (or an error on older compilers). The pub keyword satisfies this rule, while the private sealed module keeps the name unreachable from outside, which is what creates the seal.
Exercise
You add a third state Locked to the sealed State trait in the door module. List every item you must write for the state to be usable as Door<Locked>, and say whether downstream users of your crate are affected.
Show answer
Declare pub struct Locked;, write impl sealed::Sealed for Locked {}, and write impl State for Locked { const NAME: &'static str = "locked"; }. To make it useful, add transition methods in impl Door<Closed> (for example lock(self) -> Door<Locked>) and an unlock in impl Door<Locked>. Downstream users are not broken. They could not implement State before, so no existing impl can conflict, and generic code with S: State keeps compiling.