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.

RustSecurity Boundaries

Code

snippet
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

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=`.