Sub topic 8
State transitions by consuming self
This chapter assumes you know ownership and moves, impl blocks, and generic structs with PhantomData marker types. It covers how a method that takes self by value turns one state of a value into another state.
Why a transition takes self by value
In a typestate API, the state is part of the type: Door<Closed> and Door<Open> are different types. A transition therefore has to return a value of a different type. It also has to make the old value unusable. Otherwise you could hold a Door<Closed> after the door was opened, and the type would no longer describe reality.
Rust's move semantics give you this. A method with a self receiver takes ownership of the value. After the call, the caller's binding is moved and the compiler rejects any further use of it.
| Receiver | What the caller keeps | Fit for transitions |
|---|---|---|
| `&self` | The value, unchanged | No. It cannot change the type. |
| `&mut self` | The value, same type | No. A method cannot change the type of the place it borrows. |
| `self` | Nothing. The value is moved in. | Yes. It returns a value of a new type. |
A complete example
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 make this work:
openexists only inimpl Door<Closed>, andcloseexists only inimpl Door<Open>. Calling the wrong one finds no method.open(self)moves thenamefield out of the old door and builds a newDoor<Open>. The marker is zero-sized, so the transition moves only the real data.- Each
let door = ...shadows the previous binding. The old name is moved anyway, so shadowing just keeps the code readable.
What the compiler stops
Keeping a handle to the old state is the common mistake. The compiler reports a use of a moved value:
use std::marker::PhantomData;
struct Closed;
struct Open;
struct Door<State> {
_state: PhantomData<State>,
}
impl Door<Closed> {
fn open(self) -> Door<Open> {
Door { _state: PhantomData }
}
}
fn main() {
let closed: Door<Closed> = Door { _state: PhantomData };
let _opened = closed.open();
// let _again = closed.open(); // error[E0382]: use of moved value: `closed`
}A stale Door<Closed> cannot be reused, so the program cannot treat a door as closed after opening it.
Gotchas
- Struct update syntax does not work across states.
Door { _state: PhantomData, ..self }fails becauseselfhas a different type parameter. List the fields explicitly, as above. - Dropping is a transition too. A
Door<Open>that goes out of scope is simply dropped. If you need cleanup on a particular state, give each state a type that owns the resource, not the marker. - Fallible transitions need a return type that keeps the old state. If
opencan fail, returnResult<Door<Open>, Door<Closed>>. Otherwise the failed call consumed the door and the caller cannot retry. - Chains read well. Because each call returns the next state,
Door::new("a").open().close()is one expression and the type is checked at every step.
Exercise
In the Door example, why does open take self instead of &mut self, and what does the caller lose by calling it?
Show answer
A &mut self method cannot change the type of the value it borrows, so it could never turn a Door<Closed> into a Door<Open>. Taking self moves the door into the method, which returns a new Door<Open>. The caller loses the old Door<Closed> binding: the compiler rejects any later use of it with a "use of moved value" error. That is the property that keeps the type honest.
Exercise
A transition fn open(self) -> Result<Door<Open>, String> fails, and the caller wants to retry. What is wrong with this signature, and how do you fix it?
Show answer
The failed call has already consumed the Door<Closed>, and the error type String does not give it back, so the caller cannot retry. Return the old state in the error: Result<Door<Open>, Door<Closed>>, or a tuple or struct holding both the door and the error message.