Sub topic 10
Closing the set of states with a sealed trait
This chapter assumes you know Rust traits and trait bounds, associated constants, and the Door<State> typestate from earlier chapters. It also assumes you know how pub and private modules control visibility.
The problem: anyone can add a state
A typestate type like Door<S> accepts any S. If you add a State trait as a bound, any other crate can still write struct Broken; and impl State for Broken. Then Door<Broken> exists, and your API has a state you never designed for.
For a library, that matters in two ways:
- Methods you wrote for
OpenandCloseddo not cover the new state, so the type is half usable. - Adding a real new state later is a breaking change if outside code already implements the trait.
A sealed trait closes the set. Only your crate can implement it.
How sealing works
The trick uses a supertrait that outsiders cannot name.
- Create a private module with a public trait,
Sealed. - Make your public trait require
Sealedas a supertrait. - Implement
Sealedonly for your own state types.
Another crate cannot write impl State for Broken, because that requires Broken: Sealed. The module sealed is private, so the crate cannot name the trait and cannot implement it.
A complete example
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> {
_state: PhantomData<S>,
}
impl<S: State> Door<S> {
pub fn describe(&self) -> &'static str {
S::NAME
}
}
fn main() {
let door: Door<Open> = Door { _state: PhantomData };
println!("the door is {}", door.describe());
}Running it prints the door is open.
What the bound buys you
The bound S: State on Door<S> has two effects.
- A closed set.
Door<String>andDoor<u8>no longer compile, because neither implementsState. - Per-state data. The trait can carry an associated constant such as
NAME. The sharedimpl<S: State> Door<S>block can then callS::NAMEwith no runtime lookup. The compiler resolves the constant for each concrete state at compile time.
You can also put shared behavior in the trait, such as a method or an associated type. Do this only for data that every state has. Methods valid in only one state still belong in state-specific impl blocks.
Gotchas
- Sealing is a promise to yourself. Inside your crate, any code can still implement
SealedandState. Only external crates are blocked. - Do not re-export
Sealed. Apub use sealed::Sealed;would reopen the set. - Error messages are unhelpful. An outside user sees something like "the trait bound
Broken: Sealedis not satisfied", and cannot findSealedin your docs. Document in theStatetrait that it is sealed and list the allowed states. - Sealing is a decision. If you want users to define their own states, as with an extensible plugin system, do not seal. Sealing fits when your methods must handle every state.
Exercise
Exercise
A teammate writes pub trait State { const NAME: &'static str; } with no supertrait, and your crate ships Door<S: State>. A user crate defines struct Broken; and impl State for Broken { const NAME: &'static str = "broken"; }. What compiles that you did not intend, and what two changes seal the trait?
Show answer
Door<Broken> compiles, so users can create a door in a state you never designed. To seal the trait, add a private module mod sealed { pub trait Sealed {} } and change the trait to pub trait State: sealed::Sealed. Then implement sealed::Sealed for Open and Closed only. The user's impl State for Broken now fails because Broken does not implement Sealed, which the user crate cannot name.