Sub topic 8
State transitions by consuming self
This chapter assumes you know Rust ownership and moves, impl blocks on generic structs, and the PhantomData marker pattern from earlier chapters. You should also be comfortable reading compiler errors. Here you will see how a method that takes self by value changes a value's type, and why that makes invalid call orders impossible to write.
The core idea: a move turns the old state into a different value
In a typestate API, the state is a type parameter, such as Door<Open> or Door<Closed>. A method cannot change the type of a value it only borrows. A &mut self method still leaves the caller holding the same Door<Closed>.
A transition therefore takes self by value. It consumes the old value and returns a new value whose type names the new state.
use std::marker::PhantomData;
struct Open;
struct Closed;
struct Door<State> {
name: String,
_state: PhantomData<State>,
}
impl<State> Door<State> {
fn name(&self) -> &str {
&self.name
}
}
impl Door<Closed> {
fn new(name: &str) -> Self {
Door { name: name.to_string(), _state: PhantomData }
}
fn open(self) -> Door<Open> {
Door { name: self.name, _state: PhantomData }
}
}
impl Door<Open> {
fn close(self) -> Door<Closed> {
Door { name: self.name, _state: PhantomData }
}
}
fn main() {
let door = Door::new("front");
let door = door.open();
println!("{} is open", door.name());
let door = door.close();
// door.close(); // error: no method named `close` found for struct `Door<Closed>`
println!("{} is closed", door.name());
}Three things happen in open:
- The caller's
Door<Closed>is moved into the method. The caller can no longer use it. - The method moves
nameout ofselfand builds a newDoor. Only the type parameter differs, and the compiler infers it from the return typeDoor<Open>. - The caller gets the new value back and typically shadows the old binding with
let door = door.open();.
Shadowing is a convention, not a requirement. It reads well because the old name refers to a value that no longer exists. You could bind the result to a new name such as open_door.
What the compiler rejects
Two different mistakes are caught, and they produce two different errors.
The first is calling a method in the wrong state. After let door = door.close();, the type is Door<Closed>, and close exists only in the impl Door<Open> block. The compiler reports that no method named close is found for Door<Closed>. This is the state-specific impl block from the previous chapter doing its job.
The second is reusing a binding after a transition. Suppose you keep the old value around:
use std::marker::PhantomData;
struct Open;
struct Closed;
struct Door<State> {
name: String,
_state: PhantomData<State>,
}
impl Door<Closed> {
fn new(name: &str) -> Self {
Door { name: name.to_string(), _state: PhantomData }
}
fn open(self) -> Door<Open> {
Door { name: self.name, _state: PhantomData }
}
}
fn main() {
let closed = Door::new("back");
let open = closed.open();
// let again = closed.open(); // error[E0382]: use of moved value: `closed`
let _ = open;
}If you uncomment the second call, the compiler says:
error[E0382]: use of moved value: `closed`
--> src/main.rs
|
| let closed = Door::new("back");
| ------ move occurs because `closed` has type `Door<Closed>`, which does not implement the `Copy` trait
| let open = closed.open();
| ------ `closed` moved due to this method call
| let again = closed.open();
| ^^^^^^ value used here after moveThis second check matters as much as the first. Without it, a stale Door<Closed> would sit next to a Door<Open> that represents the same physical door, and the types would no longer describe reality. Ownership guarantees that exactly one value represents the object at a time.
Why the receiver type matters
| Receiver | Can it change the state type? | What the caller keeps |
|---|---|---|
| `&self` | No | The same value, same type |
| `&mut self` | No | The same value, same type |
| `self` | Yes | Nothing. The value is gone and a new one is returned. |
A &mut self method can change fields, but the value's type is fixed when it is created. Only a method that takes self can return a differently typed value and also make the old one unreachable.
The transition is free at runtime. PhantomData has size zero, so Door<Open> and Door<Closed> have the same layout. A move is a memcpy of the fields, and the optimizer usually removes it. The cost of the pattern is in the source code, not in the compiled program.
Moving fields out of self
Inside a by-value method you own self, so you may move fields out of it, as open does with self.name. You can also move out several fields, or pass some of them into the new value and drop the rest.
The struct update syntax ..self does not work across states. Door { _state: PhantomData, ..self } would fail, because self has type Door<Closed> and the new value has type Door<Open>. Rust requires the base expression of a struct update to have the same type as the struct being built. Write each field out, as the examples do. For a struct with many fields, put the state-independent data in an inner struct and move that whole value in one step:
use std::marker::PhantomData;
struct Open;
struct Closed;
struct DoorData {
name: String,
opened_count: u32,
}
struct Door<State> {
data: DoorData,
_state: PhantomData<State>,
}
impl Door<Closed> {
fn new(name: &str) -> Self {
let data = DoorData { name: name.to_string(), opened_count: 0 };
Door { data, _state: PhantomData }
}
fn open(mut self) -> Door<Open> {
self.data.opened_count += 1;
Door { data: self.data, _state: PhantomData }
}
}
impl Door<Open> {
fn close(self) -> Door<Closed> {
Door { data: self.data, _state: PhantomData }
}
}
fn main() {
let door = Door::new("garage").open().close().open();
println!("{} opened {} times", door.data.name, door.data.opened_count);
}Note mut self in open. It makes the by-value binding mutable inside the method and does not change the signature the caller sees. Chaining works because each method returns a value that the next method consumes.
Transitions that can fail
A transition sometimes depends on something that can go wrong. If start takes self and fails, the caller's value is already gone. The usual fix is to return the original value inside the error so the caller can retry or recover.
use std::marker::PhantomData;
struct Idle;
struct Running;
struct Job<S> {
name: String,
attempts: u32,
_state: PhantomData<S>,
}
struct StartError {
job: Job<Idle>,
reason: &'static str,
}
impl Job<Idle> {
fn new(name: &str) -> Self {
Job { name: name.to_string(), attempts: 0, _state: PhantomData }
}
fn start(mut self, ready: bool) -> Result<Job<Running>, StartError> {
self.attempts += 1;
if ready {
Ok(Job { name: self.name, attempts: self.attempts, _state: PhantomData })
} else {
Err(StartError { job: self, reason: "resources not ready" })
}
}
}
fn main() {
let mut idle = Job::new("backup");
let mut ready = false;
let running = loop {
match idle.start(ready) {
Ok(job) => break job,
Err(err) => {
println!("{}: {}", err.job.name, err.reason);
idle = err.job;
ready = true;
}
}
};
println!("{} running after {} attempts", running.name, running.attempts);
}This prints backup: resources not ready and then backup running after 2 attempts.
The key line is idle = err.job;. The move into start left idle uninitialized, and the error arm re-initializes it with the returned job. The compiler accepts the loop because on every path that reaches the next iteration, idle holds a value again. The Ok arm leaves the loop, so it never needs idle.
If a transition can end in one of several states, return an enum whose variants hold the different typed values. This is the point where typestate meets runtime branching, and the caller must match to learn which state they are in.
Gotchas
- Ignored results drop the value. Writing
door.open();on its own line compiles. It moves the door in, builds an open one, and drops it immediately. Add#[must_use]to the struct so the compiler warns when a transition's result is discarded. - Types that implement
Dropcannot be destructured. IfDoor<State>has aDropimpl,Door { name: self.name, .. }fails with error E0509, "cannot move out of type that implements theDroptrait". Usestd::mem::take(&mut self.name)to leave an empty value behind, or put the data in an inner struct without aDropimpl. Also remember that the old state value is dropped when the method ends, so itsDropruns on every transition. - Generic code cannot name a state it does not know. A function that takes
Door<S>for anyScan read shared methods but cannot callopenorclose. Write functions against a concrete state, or add a trait bound that provides the shared behavior. CopyandClonebreak the guarantee. If you deriveCopyon the state-carrying struct, a transition no longer invalidates the old binding. DerivingClonelets callers duplicate a value and hold two handles in the same state. Avoid both unless duplication is meaningful for your type.- Stored values lose the state. You cannot put
Door<Open>andDoor<Closed>in the sameVec<Door<_>>, because they are different types. If a collection must hold doors in mixed states, wrap them in an enum with one variant per state, or accept a runtime state field for that part of the design.
Exercises
Exercise
A teammate writes fn open(&mut self) -> Door<Open> inside impl Door<Closed>, building the new value with Door { name: self.name.clone(), _state: PhantomData }. It compiles. What guarantee has been lost compared with fn open(self) -> Door<Open>?
Show answer
The caller still holds the original Door<Closed> after the call, since &mut self only borrows it. Two values, one closed and one open, now describe the same door, and the caller can call open on the closed one again. Taking self by value moves the old value away, so only the new Door<Open> can be used. The .clone() also costs an allocation that the consuming version avoids.
Exercise
Add a lock(self) -> Door<Locked> transition that exists only on Door<Closed>, and an unlock(self, code: u32) -> Result<Door<Closed>, Door<Locked>> that returns the locked door on a wrong code (accept only the code 1234). What does the caller of unlock need to do with the Err value, and why is returning Door<Locked> in the error better than returning a String?
Show answer
The caller must match or use ?/map_err and must take the Door<Locked> from the Err to try again, otherwise the door is dropped. Returning the door in the error gives ownership back after a failed attempt, since unlock consumed it. A String error would lose the door, and the caller could not retry. A minimal implementation adds struct Locked;, then impl Door<Closed> { fn lock(self) -> Door<Locked> { Door { name: self.name, _state: PhantomData } } } and impl Door<Locked> { fn unlock(self, code: u32) -> Result<Door<Closed>, Door<Locked>> { if code == 1234 { Ok(Door { name: self.name, _state: PhantomData }) } else { Err(self) } } }.