languages/rust.md
language: rust extensions: [".rs"]
Rust — Language-Specific Review Notes
Load this file alongside rules/universal.md. Universal rules are not repeated here — only Rust-specific rules and idioms.
PR Analyzer — Rust Risk Signals
unsafe { }blocks — require explicit justification and sign-off#[allow(...)]attributes suppressing lints — verify they are justified.unwrap()/.expect("")onOptionorResultoutside of tests or prototypes- Hardcoded credentials or tokens in source
TODO/FIXMEcomments nearunsafeor ownership code
Code Quality — Rust Checks
.unwrap()used broadly in production code — prefer?,if let, ormatchclone()called excessively — may indicate ownership design issuesArc<Mutex<T>>used where a simpler ownership model would workBox<dyn Trait>used where generics (impl Trait) would avoid heap allocationpubfields on structs that should enforce invariants — use accessor methods
Security
- Flag
unsafeblocks accessing raw pointers without clear safety invariant documented in a comment - Flag
std::mem::transmute— almost always a logic error or undefined behavior; require strong justification - Flag
from_utf8_uncheckedon user-controlled data — usefrom_utf8with error handling - Flag
unwrap()on user-supplied input parsing — panics are a denial-of-service vector in server code - Flag hardcoded secrets — use environment variables or a secrets crate
Async / Concurrency
- Flag
std::sync::Mutexused in async code — usetokio::sync::Mutexto avoid blocking the async runtime - Flag
.awaitinside astd::sync::MutexGuardscope — holds the lock across an await point, blocking other tasks - Flag
spawnwithout storing theJoinHandle— panics in the spawned task are silently ignored - Flag
Arc<Mutex<T>>cloned excessively — consider message passing via channels instead - Flag blocking I/O calls (
std::fs,std::net) inside async functions — use async equivalents
Resource Management
- Flag manual
dropcalled explicitly where the natural scope boundary suffices - Flag
Rc<T>used in multi-threaded code — useArc<T>; the compiler catches this but flag in review for architecture discussion - Flag
VecorStringwith large pre-allocated capacity never trimmed — call.shrink_to_fit()if long-lived - Flag
impl Dropthat can panic — causesabortduring stack unwinding
Exception Handling
- Flag
.unwrap()in production code outside of tests — use?to propagate or handle explicitly - Flag
.expect("todo")or.expect("")— messages must explain the invariant that guarantees safety - Flag
panic!used for recoverable errors — useResult<T, E> - Flag
unwrap_or_default()where the default silently masks a real error - Prefer typed error enums (
thiserror) overBox<dyn Error>for library crates - Prefer
anyhowfor application-level error context;thiserrorfor library error types
Performance
- Flag
.clone()on large types in hot paths — review whether a reference orCow<T>would work - Flag
format!used only to create aStringfrom a literal — use.to_string()orString::from - Flag
collect::<Vec<_>>()followed immediately by.iter()— chain iterators instead - Flag
Box<T>for small types where stack allocation is fine - Flag
Mutexcontention on a hot path — considerRwLockfor read-heavy workloads or sharding
Idioms and Best Practices
Ownership
- Prefer borrowing (
&T,&mut T) over cloning wherever the lifetime allows - Use
Cow<'_, str>for functions that sometimes need to own and sometimes borrow - Prefer
impl Traitin function signatures overBox<dyn Trait>for static dispatch
Error Handling
- Use
?operator to propagate errors — avoid manualmatch Err(e) => return Err(e) - Define domain error types with
thiserrorin libraries; useanyhowin binaries - Never use
.unwrap()in library code — it panics the caller's thread
Modern Rust
- Prefer
if let/while letfor single-variant matches over fullmatch - Prefer
?overunwrapeverywhere errors are recoverable - Use
#[derive(Debug, Clone, PartialEq)]consistently on data types - Prefer
iter()chains over manual loops — they compose and optimize well - Use
clippyand treat its lints as required — flag any#[allow(clippy::...)]in review