rust
25 lines · 1 tab
Marcus Chen
Jan 2026
1 tab
struct Locked;
struct Unlocked;
struct Door<State> {
_state: std::marker::PhantomData<State>,
}
impl Door<Locked> {
fn unlock(self) -> Door<Unlocked> {
println!("Door unlocked");
Door { _state: std::marker::PhantomData }
}
}
impl Door<Unlocked> {
fn open(self) {
println!("Door opened");
}
}
fn main() {
let door = Door::<Locked> { _state: std::marker::PhantomData };
let door = door.unlock();
door.open();
}
1 file · rust
Explain with highlit
The typestate pattern uses Rust's type system to encode state machines, making invalid states unrepresentable. Each state is a separate type, and transitions consume self and return a new state. The compiler prevents calling methods that aren't valid for the current state. I use this for protocols, workflows, and resource initialization. For example, a Connection can be Closed, Open, or Authenticated, and only Authenticated can send messages. The pattern is zero-cost: states are phantom types that disappear at runtime. It's more verbose than runtime state machines, but it catches logic errors at compile time. This is especially valuable for security-critical code where state transitions must be enforced.
Related snips
ruby
class Post < ApplicationRecord
belongs_to :author, class_name: 'User'
has_many :comments, dependent: :destroy
scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
scope :draft, -> { where(published_at: nil) }
ActiveRecord scopes for reusable query logic
rails
activerecord
patterns
by Alex Kumar
1 tab
rust
struct Config<'a> {
name: &'a str,
value: &'a str,
}
fn parse_config(line: &str) -> Config {
Lifetime annotations for flexible borrowing in structs
rust
lifetimes
borrowing
by Marcus Chen
1 tab
rust
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
rust
concurrency
lock-free
by Marcus Chen
1 tab
rust
use tracing::{info, instrument};
#[instrument]
fn process_request(user_id: u64) {
info!(user_id, "Processing request");
// Work happens here
tracing for structured logging and distributed tracing
rust
observability
tracing
by Marcus Chen
1 tab
rust
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
Channels (mpsc) for message passing between threads
rust
concurrency
channels
by Marcus Chen
1 tab
rust
use clap::Parser;
#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Args {
#[arg(short, long)]
clap for CLI argument parsing with derive macros
rust
cli
clap
by Marcus Chen
1 tab
Share this code
Here's the card — post it anywhere.