Encode State Transitions With PhantomData Typestate
Build a zero-cost compile-time typestate pipeline using PhantomData<State> in 100% safe Rust so invalid transitions fail before runtime.
Code
use std::marker::PhantomData;
use std::mem::size_of;
struct Draft;
struct Approved;
struct Published;
struct Release<State> {
tag: String,
_state: PhantomData<State>,
}
impl Release<Draft> {
fn new(tag: &str) -> Self {
Self { tag: tag.to_owned(), _state: PhantomData }
}
fn approve(self, reviewer: &str) -> Result<Release<Approved>, &'static str> {
if reviewer.trim().is_empty() {
return Err("reviewer required");
}
Ok(Release { tag: self.tag, _state: PhantomData })
}
}
impl Release<Approved> {
fn publish(self) -> Release<Published> {
Release { tag: self.tag, _state: PhantomData }
}
}
impl Release<Published> {
fn label(&self) -> &str {
&self.tag
}
}
fn main() {
let draft = Release::<Draft>::new("v1.4.0");
println!("Draft err: {:?}", Release::<Draft>::new("v1.4.0").approve(""));
let approved = draft.approve("alice").expect("valid reviewer");
let live = approved.publish();
println!("Published release: {}", live.label());
println!(
"Zero marker overhead: String={} Release={}",
size_of::<String>(),
size_of::<Release<Published>>()
);
}Annotated execution — Encode State Transitions With PhantomData Typestate
Logic execution stays neatly scoped inside functions new, approve, publish and label — everything else is wiring.
The function returns Result, so handling the error arm is not optional.
Watch out for
- Built zero-dependency from start to finish — omits registries and lockfiles altogether.
- The
?operators are load-bearing: delete one and the error handling becomes your job.
Using it
Lead function signature defines fn new(tag: &str) -> Self
Stdout records present markers — Draft err:, Published release:, Zero marker overhead: String= — when the file runs.
There are 4 calls inside main — new, approve, publish and label — executed top to bottom.
Key statements
return Err("reviewer required");
Ok(Release { tag: self.tag, _state: PhantomData })
}
fn publish(self) -> Release<Published> {
Release { tag: self.tag, _state: PhantomData }
}
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- Is there exception handling?
- No panics — `Result` values carry the failure.
- What does Encode State Transitions With PhantomData Typestate print when run?
- Running the file directly is enough — expect labeled output lines such as `Draft err:`, `Published release:`, `Zero marker overhead: String=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.