rust-typestate-and-tokenslisted
Install: claude install-skill takurot/rust-skills-comprehensive
# Rust Typestate Pattern & Token Types
Two related techniques for moving a runtime check into the type system so misuse becomes a
compile error: **typestate** (encode *which step of a protocol* a value is in) and **tokens**
(a value that exists only as *proof* something was checked). Neither is in `rust-patterns`.
## Typestate pattern
Encode part of a value's runtime state in its type, so each state exposes only the operations
valid for it — the previous state's methods are consumed and simply don't exist on the next
type.
```rust
struct Serializer { output: String }
struct SerializeStruct { serializer: Serializer }
impl Serializer {
fn serialize_struct(mut self, name: &str) -> SerializeStruct {
writeln!(&mut self.output, "{name} {{").unwrap();
SerializeStruct { serializer: self }
}
fn finish(self) -> String { self.output }
}
impl SerializeStruct {
fn serialize_field(mut self, key: &str, value: &str) -> Self {
writeln!(&mut self.serializer.output, " {key}={value};").unwrap();
self
}
fn finish_struct(mut self) -> Serializer { /* closes the struct, returns to Serializer */ }
}
```
`Serializer::default().serialize_struct("User").finish()` — calling `finish()` before
`finish_struct()` isn't a runtime "wrong state" error, it's a **method that doesn't exist on
that type**, caught at compile time. Each transition method takes `self` by value, consuming
the current state so it can't be reused after moving to the next one.