← ClaudeAtlas

rust-typestate-and-tokenslisted

Design compile-time state machines (typestate pattern) and proof-of-permission token types in Rust. Use when a value's valid operations depend on which step of a protocol it's in (builders, serializers, connection handshakes), when you want "calling this without permission" to be a compile error instead of a runtime check, or when indexes/handles need to be proven valid without repeated bounds checks.
takurot/rust-skills-comprehensive · ★ 0 · AI & Automation · score 71
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.