Sub topic 7
Methods that exist only in certain states
This chapter assumes you know generic structs, impl blocks, and how PhantomData<T> and marker types work from the earlier chapters. Here you will use that foundation to make a method exist only when a value is in the right state. The compiler then rejects a call that does not belong, and no runtime check is involved.
The core idea: impl blocks on concrete type arguments
An impl block normally names a type parameter:
impl<T> Wrapper<T> { /* ... */ }This block applies to every Wrapper<T>. You can also write an impl block for one specific type argument:
impl Wrapper<i32> { /* ... */ }Methods in this block exist only on Wrapper<i32>. A Wrapper<String> does not have them. Typestate depends on this rule. If the state is a type parameter, each state can have its own impl block, and each block defines the methods valid in that state.
A first example: two states, three kinds of impl
Here is a door with two states. It has one shared block and one block per state.
use std::marker::PhantomData;
struct Open;
struct Closed;
struct Door<State> {
name: String,
_state: PhantomData<State>,
}
// Available in every state.
impl<State> Door<State> {
fn name(&self) -> &str {
&self.name
}
}
// Available only when the door is open.
impl Door<Open> {
fn new(name: &str) -> Self {
Door { name: name.to_string(), _state: PhantomData }
}
fn walk_through(&self) -> String {
format!("you walk through the {} door", self.name)
}
}
// Available only when the door is closed.
impl Door<Closed> {
fn new(name: &str) -> Self {
Door { name: name.to_string(), _state: PhantomData }
}
fn knock(&self) -> String {
format!("knock, knock on the {} door", self.name)
}
}
fn main() {
let open = Door::<Open>::new("front");
let closed = Door::<Closed>::new("back");
println!("{}", open.walk_through());
println!("{}", closed.knock());
println!("{} and {}", open.name(), closed.name());
}name is in the generic block, so both doors have it. walk_through exists only on Door<Open>, and knock only on Door<Closed>.
Calling a method in the wrong state fails at compile time:
let closed = Door::<Closed>::new("back");
closed.walk_through();error[E0599]: no method named `walk_through` found for struct `Door<Closed>` in the current scope
= note: the method was found for
- `Door<Open>`The error names the state you are in. It also lists the states where the method does exist, which usually tells you what to fix.
How the compiler picks a method
The compiler resolves a method call in a fixed order:
- It looks at the receiver's full type, including its type arguments, such as
Door<Closed>. - It collects every inherent
implblock that could apply to that type. - It looks for the method name among them.
The shared block impl<State> Door<State> matches every state. The block impl Door<Open> matches only Door<Open>. When you call closed.knock(), the Door<Open> block is never a candidate, so the method is not found.
The marker type is the only difference between the two doors. Door<Open> and Door<Closed> are different types with identical layout. Because they are different types, they can have different methods.
Same name, different behavior per state
Two state-specific blocks can define a method with the same name. They apply to different types, so they do not conflict. The two new functions above already do this. The same works for methods:
use std::marker::PhantomData;
struct Open;
struct Closed;
struct Door<State> {
_state: PhantomData<State>,
}
impl Door<Open> {
fn status(&self) -> &'static str {
"open: you can walk through"
}
}
impl Door<Closed> {
fn status(&self) -> &'static str {
"closed: you need to open it first"
}
}
fn main() {
let a: Door<Open> = Door { _state: PhantomData };
let b: Door<Closed> = Door { _state: PhantomData };
println!("{}", a.status());
println!("{}", b.status());
}This is static dispatch resolved at compile time. No match and no vtable are involved.
Associated functions without a receiver, such as new, need extra care. When two blocks both define Door::new, the path Door::new("x") does not say which block you mean. Write the state explicitly with Door::<Closed>::new("x"). This is why the first example calls Door::<Open>::new.
Where overlap becomes an error
The compiler rejects a method name that a generic block and a specific block both define for the same type:
impl<State> Door<State> {
fn status(&self) -> &'static str { "any" }
}
impl Door<Open> {
fn status(&self) -> &'static str { "open" } // error[E0592]: duplicate definitions with name `status`
}Inherent methods have no specialization. A specific block cannot override a generic one, because Door<Open> would then have two candidates named status. Put a method either in the generic block or in the specific blocks, never both.
Grouping states with a trait bound
Sometimes a method should exist in several states but not all of them. Writing one block per state repeats the code. Instead, define a trait that the chosen states implement and bound the impl block on it.
The next example has three states and puts knock in the two states where the door is shut. It also moves the type into a module so the fields stay private:
mod door {
use std::marker::PhantomData;
pub struct Open;
pub struct Closed;
pub struct Locked;
/// States in which the door is shut.
pub trait Shut {}
impl Shut for Closed {}
impl Shut for Locked {}
pub struct Door<State> {
name: String,
_state: PhantomData<State>,
}
impl<State> Door<State> {
pub fn name(&self) -> &str {
&self.name
}
}
impl Door<Open> {
pub fn new(name: &str) -> Self {
Door { name: name.to_string(), _state: PhantomData }
}
pub fn status(&self) -> &'static str { "open" }
pub fn walk_through(&self) -> String {
format!("you walk through the {} door", self.name)
}
}
impl Door<Closed> {
pub fn new(name: &str) -> Self {
Door { name: name.to_string(), _state: PhantomData }
}
pub fn status(&self) -> &'static str { "closed" }
}
impl Door<Locked> {
pub fn new(name: &str) -> Self {
Door { name: name.to_string(), _state: PhantomData }
}
pub fn status(&self) -> &'static str { "locked" }
}
// Available in Closed and Locked, but not in Open.
impl<State: Shut> Door<State> {
pub fn knock(&self) -> String {
format!("knock, knock on the {} door", self.name)
}
}
}
use door::{Closed, Door, Locked, Open};
fn main() {
let open = Door::<Open>::new("front");
let closed = Door::<Closed>::new("back");
let locked = Door::<Locked>::new("vault");
for status in [open.status(), closed.status(), locked.status()] {
println!("{status}");
}
println!("{}", open.walk_through());
println!("{}", closed.knock());
println!("{}", locked.knock());
// open.knock(); // error: the trait bound `Open: Shut` is not satisfied
}The error for open.knock() now mentions an unmet bound instead of a missing method. The cause is the same: Open is not in the set of allowed states.
Because the fields are private, code outside mod door cannot write Door { ... } directly. It must use one of the constructors, and each constructor fixes the starting state. This matters in practice. If a public constructor like fn new() -> Door<S> were generic over the state, any caller could create a Door<Open> out of nothing and bypass the rules.
Choosing the right kind of block
| Block | Applies to | Use it for |
|---|---|---|
| `impl<S> Door<S>` | Every state | Getters and behavior that never depends on the state |
| `impl Door<Open>` | Exactly one state | Methods and constructors that make sense in one state only |
| `impl<S: Shut> Door<S>` | Every state that implements the trait | Methods shared by a subset of states |
Trait implementations follow the same rules
Trait implementations can also target one state. This lets a type be Display in one state and not in another:
use std::fmt;
use std::marker::PhantomData;
struct Open;
struct Closed;
struct Door<State> {
_state: PhantomData<State>,
}
impl fmt::Display for Door<Open> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "an open door")
}
}
impl fmt::Display for Door<Closed> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "a closed door")
}
}
fn main() {
let a: Door<Open> = Door { _state: PhantomData };
let b: Door<Closed> = Door { _state: PhantomData };
println!("{a}, {b}");
}Be careful with derives. #[derive(Clone)] on Door<State> adds the bound State: Clone, so it works only if the marker type is Clone too. Either derive the traits on your marker types as well, or write the implementation by hand without the extra bound.
Common mistakes
- Putting a method in both a generic and a specific block. This causes E0592. Move it to one place.
- Calling an ambiguous associated function. Write
Door::<Closed>::new(...)instead ofDoor::new(...). - Exposing a generic constructor. A public
fn new<S>() -> Door<S>lets callers choose any state. Keep fields private and give each state its own constructor. - Adding methods in another crate. Inherent
implblocks must live in the crate that defines the type. Other crates can add behavior only through traits.
Exercises
Exercise
A struct Light<State> has impl<State> Light<State> { fn watts(&self) -> u32 { 10 } } and impl Light<On> { fn watts(&self) -> u32 { 60 } }. Does this compile? If not, what is the error and how do you fix it?
Show answer
It does not compile. Both blocks define watts for Light<On>, so the compiler reports E0592 (duplicate definitions). Inherent methods cannot be overridden by a more specific block. Fix it by removing watts from the generic block and defining it in one block per state (for example impl Light<On> and impl Light<Off>). Alternatively, keep a single watts in the generic block and read the state from a trait constant.
Exercise
You have the states Draft, Reviewed and Published for a Post<State>. The method preview must exist in Draft and Reviewed but not in Published. Which kind of impl block do you write, and what else do you define?
Show answer
Define a trait such as Editable and implement it for Draft and Reviewed. Then write impl<State: Editable> Post<State> { fn preview(&self) -> String { /* ... */ } }. Calling preview on a Post<Published> fails because Published: Editable is not satisfied. To stop other crates from adding states to the group, seal the trait.