Rust Patterns Basics
10 examples to get you started with Rust Patterns - 7 basic and 3 intermediate.
Prerequisites
- Rust 1.97.0 (edition 2024)
- Comfort with ownership,
Option/Result, and traits
Basic Examples
1. Newtype for Safety
struct UserId(u64);
struct OrderId(u64);
// cannot pass OrderId where UserId expectedRelated: The Newtype Pattern
2. Builder for Complex Config
let client = Client::builder()
.timeout(Duration::from_secs(5))
.build()?;Related: Builder Pattern
3. RAII Guards
struct LockGuard<'a>(&'a mut State);
impl Drop for LockGuard<'_> {
fn drop(&mut self) { /* release */ }
}Related: RAII & Drop Guards
4. From/Into Conversions
impl From<u64> for UserId {
fn from(id: u64) -> Self { UserId(id) }
}
let id: UserId = 42.into();Related: From/Into & TryFrom
5. Extension Traits
trait StrExt {
fn trimmed(&self) -> &str;
}
impl StrExt for str {
fn trimmed(&self) -> &str { self.trim() }
}Related: Iterator & Extension Traits
6. Typestate Encoding
struct Connection<State> { /* ... */ }
struct Open;
struct Closed;Related: Typestate Pattern
7. Interior Mutability
use std::cell::RefCell;
let cache = RefCell::new(HashMap::new());Related: Interior Mutability Patterns
Intermediate Examples
8. Error Context with ?
fn load() -> Result<Data, Error> {
let raw = read_file().context("read config")?;
parse(raw).context("parse config")
}9. Iterator Chains
let active: Vec<_> = users.iter().filter(|u| u.active).map(|u| u.id).collect();10. Anti-Patterns to Avoid
unwrap()in library codeclone()to appease borrow checkerRc<RefCell<_>>everywhere
Related: Common Anti-Patterns
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.