Book Chapters
From fundamentals to advanced patterns, each chapter builds your Rust expertise
Core Patterns
- 1 Memory & Ownership Patterns
- 2 Struct & Enum Patterns
- 3 Trait Design Patterns
- 4 Generics & Polymorphism
- 5 Builder & API Design
- 6 Lifetime Patterns
Functional & Matching
- 7 Functional Programming
- 8 Pattern Matching & Destructuring
- 9 Iterator Patterns & Combinators
- 10 Reference Binding
- 11 Error Handling Architecture
Data Structures
- 12 Vec & Slice Manipulation
- 13 String Processing
- 14 HashMap & HashSet Patterns
- 15 Advanced Collections
Concurrency
- 16 Threading Patterns
- 17 Async Runtime Patterns
- 18 Atomic Operations & Lock-Free
- 19 Parallel Algorithms
Advanced Memory
- 20 Smart Pointer Patterns
- 21 Unsafe Rust Patterns
I/O & Serialization
- 22 Synchronous I/O
- 23 Async I/O Patterns
- 24 Serialization Patterns
Metaprogramming
- 25 Declarative Macros
- 26 Procedural Macros
- 27 FFI and C Interop
Real-World Systems
- 28 Network Programming
- 29 Database Patterns
- 30 Testing and Benchmarking
Appendices
- 31 Appendix A: Quick Reference
- 32 Appendix B: Design Patterns
- 33 Appendix C: Anti Patterns
Companion Workbook
87 hands-on projects to cement your understanding through practice
lru-cache
Implement an LRU cache that keeps recently accessed items and evicts the least-used entry when the capacity limit is reached.
expression-parser-arena
Build an arithmetic-expression parser that uses arena (bump) allocation so parsed trees share storage.
string-interning
Create a string interning system that stores each unique string once and hands out reusable references.
generic-data-structures
Assemble a const-generic collection toolkit whose sizes live in the type system and incur zero runtime cost.
memory-pool
Write a pool allocator that pre-allocates a big block and serves fixed-size slots quickly to hot code paths.
reference-count
Re-implement reference counting to learn how Rc/Arc-like structures manage shared ownership.
safe-configuration
Define configuration newtypes and builders that prevent invalid server configs at compile time.
streaming-iterator-hrtb
Implement a streaming iterator that yields borrowed data via higher-ranked trait bounds and GATs.
validated-wrappers
Implement validated wrapper types (Email, Url, NonEmptyString, PositiveInt) for type-safe domain modeling.
zero-copy-protocol
Parse text by borrowing slices from the input so tokens remain valid without allocations.
parser-combinator
Build a functional parser combinator library with composable parsing primitives.
middleware-pipeline
Create a functional middleware pipeline for request/response processing.
json-parser-validator
Parse JSON into an AST and validate against schemas using pattern matching.
network-packet-inspector
Inspect multi-layer network packets, enforce firewall rules, and detect malicious patterns.
order-state-machine
Model an order workflow with enums so illegal state transitions can't compile.
regex-engine
Build a regex engine that parses patterns, supports captures/alternation, and backtracks correctly.
csv-parser
Stream massive CSV files using iterators that handle quoting and keep memory usage flat.
pagination-iterator
Expose paginated REST endpoints as lazy iterators that fetch pages on demand.
plugins
Load runtime-selected plugins safely so user code can extend the host app.
config-validator
Parse TOML/JSON configs and emit precise schema errors for bad inputs.
parser-combinator-traits
Build parser combinators with associated types so small parsers compose ergonomically.
web-scraper-retry-breaker
Crawl many URLs concurrently with retries, rate limits, and circuit breakers.
generics-queue
Implement a generic priority queue that accepts any Ord payload.
csv-processor
Process multi-gig CSVs by chunking, transforming, validating, and batching inserts efficiently.
timeseries
Analyze time-series streams by computing sliding-window statistics in O(n).
binary-search
Provide binary-search helpers that power fast queries over sorted data.
log-parser
Parse huge log files into structured events with zero-copy string handling.
text-editor-gap-buffer
Implement a gap-buffer editor core that makes insert/delete near the cursor cheap.
boyer-moore-search
Apply Boyer-Moore substring search to find patterns efficiently in large texts.
analytics-engine
Maintain real-time analytics over streaming events with HashMaps for aggregations.
custom-hash-functions
Create custom hashers for spatial/geographic data to keep maps performant and correct.
cache-alternative-maps
Compare alternative map types to build a multi-tier cache with varied access patterns.
autocomplete
Build a trie-based autocomplete engine that returns suggestions fast.
queue-crossbeam
Use crossbeam to implement a lock-free MPMC queue for parallel workloads.
scheduling
Prioritize and schedule jobs via binary heaps that respect deadlines.
image-processor
Fan out CPU-heavy image filters onto a thread pool for throughput.
producer-consumer
Chain processing stages via channels to demonstrate producer/consumer backpressure.
shared-counter
Coordinate shared counters across threads using Arc + Mutex.
webscraper
Scrape the web asynchronously while respecting rate limits and handling failures.
event-stream
Consume multiple event streams, transform them, and fan results out in real time.
task-scheduler
Manage async tasks with priorities, deadlines, and retry policies.
image-processing-async
Build an async pipeline that watches directories and processes images concurrently.
metrics
Record metrics from many threads using lock-free atomics instead of mutexes.
treiber-stack
Implement a lock-free Treiber stack using CAS loops and hazard pointers.
ring-buffer
Implement a wait-free ring buffer for producer/consumer communication.
sorting
Build a fork-join parallel sorting library that scales across cores.
graph
Traverse graphs in parallel while balancing irregular workloads.
map-reduce
Implement a mini MapReduce engine that distributes log analysis jobs.
kafka
Simulate a Kafka-style event pipeline that handles millions of messages per second.
tokenizer
Build character-, word-, and BPE-tokenizers for ML pipelines.
matrix-multiplication
Optimize matrix multiplication from naive O(n^3) up to tiled/SIMD/GPU variants.
rc-dom
Model a DOM tree with Rc/Weak so nodes share ownership and can navigate parents.
object-pool
Reuse expensive objects via a smart-pointer-backed pool instead of reallocating.
cow
Design copy-on-write structures that share data until a write occurs.
cpu-optimization-convolution
Optimize 2D convolutions with cache blocking, SIMD, and threading.
build-system-pipeline
Orchestrate compiler stages, capture logs, and re-run only changed targets.
file-sync-rsync
Synchronize directories rsync-style by hashing chunks and copying only deltas.
version-control-git
Implement Git primitives (blobs, trees, commits, refs) to track history and sync repos.
async-http-proxy
Build an async HTTP proxy with connection pooling, backpressure, timeouts, and health checks.
chat-server-broadcast
Broadcast chat messages to many clients while handling backpressure and disconnects.
ini
Parse and emit INI files with serde-friendly structures and validation.
performance
Benchmark JSON, Bincode, and MessagePack to compare size vs speed.
migration
Migrate old serialized config formats to the latest schema transparently.
query-builder
Generate SQL query builders with declarative macros for a type-safe DSL.
test-framework
Build a macro-driven test harness that expands compact specs into full suites.
config-dsl
Create a declarative config DSL macro that produces typed structs at compile time.
orchestration
Use procedural macros to define deployment/orchestration manifests in Rust.
spring-framework-macros
Mimic Spring Boot annotations with procedural macros for DI and routing.
ffi-c
Wrap C's qsort/bsearch in safe Rust so arbitrary types can interop.
ffi-python
Expose a Rust text-processing library as a Python module via PyO3.
rust-assembly-optimization
Study Rust's assembly output and inject inline asm to tighten hotspots.
chat-server
Grow a simple echo server into a full chat service with multiple protocols.
udp-game-server
Build a UDP-based multiplayer server with service discovery and reliability.
distributed-kv-store
Create a distributed KV store with replication, persistence, and leader election.
collaborative-editor
Sync shared documents via CRDT-like techniques for concurrent editing.
task-queue
Persist a durable task queue where workers lease and process jobs safely.
blog-api
Expose CRUD blog APIs backed by SQLx with compile-time query checking.
multi-tenant-saas
Partition tenant data and enforce tenant-aware queries in a SaaS schema.
coverage-analyzer
Instrument Rust code to report line/branch/function coverage from tests.
mutation-testing
Flip AST nodes deliberately and ensure the test suite fails appropriately.
property-test-generator
Auto-generate property tests using proptest based on function signatures.
profiler
Profile Rust programs by sampling CPU time, memory allocations, and call stacks.
data-pipeline
Build a streaming data pipeline tuned for cache locality and SIMD throughput.
cache-structures
Compare cache-friendly data layouts to maximize CPU efficiency.
embedded-hal-sensor-driver
Hardware Abstraction Layer using traits for embedded systems.
embedded-realtime-logger
Zero-copy DMA transfers for ADC, UART, and SPI in embedded contexts.
embedded-interrupt-coordinator
Priority-based interrupt management for embedded Rust applications.
Ready to Master Rust Patterns?
Get the complete book with 33 chapters and 87 hands-on projects
Get the Book on Leanpub