Common Anti-Patterns
Recognize Rust anti-patterns early: they compile but create panics, perf debt, or unmaintainable graphs.
Busca en todas las páginas de la documentación
Recognize Rust anti-patterns early: they compile but create panics, perf debt, or unmaintainable graphs.
// Anti-pattern
let data = fetch().unwrap().clone().clone();
// Prefer
let data = fetch().context("fetch")?;
process(&data);When to reach for this: Code review, clippy cleanup, and post-incident refactors.
| Anti-pattern | Problem | Fix |
|---|---|---|
unwrap() in library | panic for callers | ? + typed errors |
clone() to appease borrow checker | hidden cost | restructure ownership, Arc, or lifetimes |
Rc<RefCell<T>> graph | runtime borrow panics | arena, indices, or unique ownership |
String everywhere | allocations | &str, Cow, Arc<str> |
async fn blocking | stalled runtime | spawn_blocking |
dyn Error everywhere | erasure, no context | concrete error enums + thiserror |
What this demonstrates:
unwrap_used, redundant_clone)Use newtypes and enums instead of String status codes. unwrap in tests and prototypes only with plan to remove.
std::thread::sleep in async, block_on inside runtime, unbounded spawn without backpressure.
expect("invariant: ...") or Result.
| Alternative | Use When | Don't Use When |
|---|---|---|
? operator | Fallible ops | Truly impossible invariant (document) |
| Typestate | illegal states | trivial two-state bool |
| Channels | task isolation | synchronous hot loop |
Acceptable for bootstrap fatal misconfig with message.
Often required for 'static; clone once before spawn.
Single-thread UI may use Rc; still prefer clear ownership.
Never on reachable paths; use Err or feature gate.
Extra alloc; chain iterators if possible.
OK at boundary; inject generics in core domain.
Legacy pattern; prefer OnceLock/LazyLock.
Lose type safety; parse into structs early.
Prefer tokio tasks in async apps; threads for CPU pools.
clippy deny in CI, review checklist, arch tests.
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+.
Revisado por Chris St. John·Última actualización: 19 jul 2026