references/effective-rust.md
GitHubEffective Rust (digest)
Source: Effective Rust by David Drysdale (O'Reilly, 2024), free online at
https://www.lurklurk.org/effective-rust/ . Thirty-five items on writing Rust well.
Read this when weighing alternatives: generics vs trait objects, Result vs panic,
iterators vs loops, how to get past the borrow checker, dependency and CI policy.
The book targets Rust 1.70 to 1.76; anything it calls "upcoming" has long since landed.
Types (Items 1-9)
- Use the type system to express your data structures. Replace "must be (0,0,0) if
monochrome" comments with an enum that carries the data.
Optionfor absence, never sentinels. Fallible results are alwaysResult<T, E>. An enum instead of aboolparameter when a third option could ever arrive; a newtype when it will always be boolean. - Use the type system to express common behavior. Accept trait types rather than
concrete ones when flexibility matters. For closures use the most general
Fn*bound that works:FnOnceif called once,FnMutif it mutates,Fnotherwise. PreferFn*bounds to barefnpointers, which cannot capture state. Marker traits (a method-lessStableSort: Sort) express guarantees a signature cannot. - Prefer
OptionandResulttransforms over explicitmatch.map,and_then,ok_or,map_err,unwrap_or_else,as_ref(), and?.ResultbeatsOptionwhen the failure could carry useful information.unwrapandexpectare decisions to panic (Item 18). - Prefer idiomatic
Errortypes. Implementstd::error::Error(requiresDebug+Display;source()exposes causes). Preserve sub-errors with an enum plus aFromimpl per inner error (thiserrorgenerates this). When they need not be preserved, applications useanyhow; keepanyhowout of library public APIs. A bareStringcannot implementError(orphan rule), so wrap it. - Understand type conversions. Implement
From(givesIntofree);TryFromonly when a conversion can fail. In bounds useInto<T>so both kinds of impl are accepted. Preferfrom/intooveras, which silently permits lossy casts, except where exact cast semantics are the point (C interop). - Embrace the newtype pattern.
PoundForceSeconds(f64)vsNewtonSeconds(f64)can't be mixed; an alias doesn't prevent it. Newtypes also let you implement a foreign trait for a foreign type. Cost: inner trait impls are lost and must be re-derived or forwarded.#[repr(transparent)]keeps the layout identical. - Use builders for complex types.
Defaultwith..Default::default()when most fields have sensible defaults; a builder when there are optional or validated fields. Consuming builders (fn x(self) -> Self) are most ergonomic but can't be staged conditionally or reused.&mut selfbuilders allow staging but need a namedletbinding, and a repeatablebuild(&self)must construct fresh values. - Familiarize yourself with reference and pointer types.
&Tis a pointer the compiler guarantees valid, aligned, and borrow-checked.Box<T>for single-owner heap data;Rc/Arcfor shared ownership (withWeakto avoid cycles);Cell/RefCellorMutex/RwLockfor interior mutability.RefCellmoves borrow checks to runtime, so usetry_borrowwhere a panic is unacceptable. Choose the mutation granularity you need:Rc<RefCell<Vec<T>>>vsRc<Vec<RefCell<T>>>. - Consider iterator transforms instead of explicit loops. Source, adapters
(
filter,take,map,zip), consumer (sum,fold,find,any,collect). Propagate the first error by collecting intoResult<Vec<_>, _>and applying?. Keep a loop when the body is large or does several jobs, when early returns are awkward inside closures, or when the transform is forced. Measure when it matters.
Traits (Items 10-13)
- Familiarize yourself with standard traits. Derive
Clone,Copy,Debug,PartialEq,Eq,PartialOrd,Ord,Hash,Defaultwhen every field supports them; hand-implement only where the derived behavior is wrong. SkipClonefor unique-access resources and secret key material;Copyonly when a bitwise copy is valid and fast. PairEqwithPartialEq(not for floats), keepHashconsistent withEq, never shipPartialOrdwithout a matchingOrd. - Implement
Dropfor RAII patterns. Any type holding a resource that must be released (file descriptor, lock, raw memory) implementsDrop. Scope guards with blocks so locks are not held longer than needed.dropcan't return an error, so provide a separate falliblerelease(). Calldrop(x), neverx.drop(). - Understand the trade-offs between generics and trait objects. Prefer generics.
Monomorphization gives static dispatch and speed but one code copy per type (bigger
binaries, slower builds). Trait objects (
&dyn,Box<dyn>) use one copy plus a vtable and suit heterogeneous collections, code-size or compile-time limits, or code loaded at runtime. Object safety: no generic methods, noSelfin args or returns beyond the receiver, unless markedwhere Self: Sized. - Use default implementations to minimize required trait methods. Few required
methods; defaults for everything derivable (as
Iteratorbuilds 50+ methods onnext()). Defaults can carry bounds (cloned()only forCloneitems). Adding a defaulted method is usually backward compatible.
Concepts (Items 14-20)
- Understand lifetimes. A reference may not outlive its referent. Elision covers
a single input reference lending to the output, and methods lending
&self's lifetime. Otherwise name them. A struct holding a reference needs a lifetime that propagates to every container, so prefer owning data.'staticis for globals or deliberately leaked data (Box::leak). - Understand the borrow checker. Any number of
&Tor exactly one&mut T, never both, and non-lexical lifetimes end a reference at its last use. Coping tactics: extend a temporary with a namedletor shorten with a block; split a complex expression into typed intermediates; redesign ownership by cloning small immutable data, using an owningVecwith indices (fragile), orRc/RefCellwithWeakback-pointers. Avoid self-referential structs (ouroborosif unavoidable). - Avoid writing unsafe code. Use std and crates.io first, where battle-tested
unsafealready lives (Rc,Mutex,Pin,cxx). When unavoidable: confine it to a small wrapper with a safe API, document each block's preconditions in a safety comment, minimize each block, enableunsafe_op_in_unsafe_fn, write extra tests, run Miri. - Be wary of shared-state parallelism.
Send/Syncand the borrow checker eliminate data races in safe code; deadlocks and logic races remain. Prefer message passing. When sharing: keep data with linked invariants under one lock, keep lock scopes small, never call closures while holding a lock, never return aMutexGuardto a caller, add deadlock detection to CI. A documented lock hierarchy is a last resort. - Don't panic. Prefer
Result; panic is for unrecoverable bugs or corrupted state. Rule of thumb:panic!,unwrap(),expect()are acceptable when you controlmain, because no further caller exists. Where a panic is justified, pair an infallible function (documented under# Panics) with a fallible one.catch_unwindis not an exception substitute: it does nothing underpanic = "abort"and can leave state inconsistent. Use it at FFI boundaries only. - Avoid reflection. No general runtime reflection.
type_nameis diagnostic only;TypeId/Any::downcast_refwork only on values already wrapped asdyn Any. Encode required behavior as traits, marker traits for properties, derive macros for compile-time generation. - Avoid the temptation to over-optimize. Design for usability first: a type that
owns a
Vec<u8>avoids lifetime propagation, and copying small data is usually fine. Add allocations or clones only after benchmarks show they matter;Rc/ArcwithRefCell/Mutexare legitimate tools. Exception:Copy. Derive it for small bitwise-copyable types and never for large or non-trivial ones.
Dependencies (Items 21-26)
- Understand what semantic versioning promises.
"1.2.3"means^1.2.3;"~"allows patches only;"="pins;"*"accepts anything. Breaking changes: removing public items, adding a variant to a matchable enum (unless#[non_exhaustive]), adding a public field to a publicly constructible struct, making a trait non-object-safe, adding a blanket impl. License and default feature set are API. Deprecate in a minor release before removing in a major one. - Minimize visibility. Private by default;
pub(crate),pub(super),pub(in path)beforepub. Widening later is minor; narrowing is breaking. Keep fields private;pubon an enum or trait exposes all variants or methods. - Avoid wildcard imports. Don't glob-import crates you don't control; a minor
release can add a clashing name (error E0034). Fine for
use super::*in tests, modules you own, and a deliberately curated prelude. If you glob a dependency anyway, pin it. - Re-export dependencies whose types appear in your API. A caller on a different
semver-incompatible version of
randgets a confusing "trait bound not satisfied". Re-export (pub use rand;) so callers can name the matching version, and think hard before exposing foreign types at all. - Manage your dependency graph. Cargo allows semver-incompatible versions of a crate
to coexist, never two compatible ones. Commit
Cargo.lockfor binaries. Prefer"1"or"1.4.23"to"=1.2.3"or"*". Usecargo tree(--invert,--duplicates,--edges features),cargo-deny,cargo-udeps. Every dependency costs build time, binary size, and supply-chain exposure, includingbuild.rsand proc macros. - Be wary of feature creep. Features must be additive because Cargo unifies them
across the graph. Don't feature-gate public struct fields or trait methods. Feature
names share a namespace with crate names. Each independent feature doubles the
configurations; CI should cover the combinations that matter. Model: a
stdorallocfeature on ano_stdbase.
Tooling (Items 27-32)
- Document public interfaces.
///and//!, cross-reference with[`Name`],# Examples,# Panics,# Safetysections. Describe what the signature cannot express (preconditions, errors, panics, why), not the types.cargo doc --open; consider denyingbroken_intra_doc_links; avoid rushed docs written only to silencemissing_docs. - Use macros judiciously. Only when a function or generic cannot do the job, or to
keep parallel code in sync (one table generating an enum plus
group(),text(),TryFrom). Macros can insertreturn,?, or mutations at the call site, so keep control flow visible, and bind expression arguments withletto avoid re-evaluation. Prefer a derive macro to a proc macro that emits a new type. Checkstrum,enumn,num_enumfirst. - Listen to Clippy. Keep the code warning-free. Fix rather than suppress; where a
lint is genuinely wrong, a narrow
#[allow(clippy::..)].cargo clippy -- -Dwarningsin CI. Read the full lint list, including default-off lints such asas_conversions, to learn idiom. - Write more than unit tests. Unit tests in
#[cfg(test)] mod tests(see private items); integration tests intests/(public API only); doc tests; examples (cargo test --examples). Benchmarks withstd::hint::black_box.cargo-fuzzfor untrusted input. Write a failing test before fixing a bug. Test every feature combination and platform with distinct code. - Take advantage of the tooling ecosystem.
cargo fmt,check,clippy,doc,bench,update,tree,metadata;rust-analyzer;cargo-expand,cargo-tarpaulin,cargo-udeps,cargo-deny,cargo-semver-checks, Miri. Wire useful tools into CI; fast, false-positive-free ones into the editor. - Set up CI. Build, run every test type,
cargo clippy -- -Dwarnings,cargo fmt --check,cargo doc,cargo-deny. Pin the toolchain withrust-toolchain.toml, build every feature combination, check the MSRV, build ano_stdtarget, detect generated-code drift. Remove flaky tests; make every check runnable locally; add a CI check for a process problem before fixing it.
Beyond standard Rust (Items 33-35)
- Consider making library code
no_stdcompatible.corehasOption,Result, iterators;allocaddsBox,Rc,Arc,Vec,String,BTreeMap.HashMapandMutexneed the OS. Often juststd::path changes andBTreeMap. Guard with a CI cross-compile (thumbv6m-none-eabi); expose additivestd/allocfeatures, never ano_stdfeature. Prefertry_reservewhere memory is limited. - Control what crosses FFI boundaries. Calls into C are
unsafe.extern "C"blocks,#[link]orbuild.rs, sized types,#[repr(C)],CString/CStr. Allocate and free on the same side; wrap C-owned pointers in an RAII type; check null and returnResult; keep unsafe inside the wrapper. Exported functions needextern "C",#[no_mangle], a unique prefix;Box::into_raw/from_rawfor ownership transfer; never return stack pointers; stop panics withcatch_unwind. - Prefer
bindgento manual FFI mappings. Generate declarations from C headers (--allowlist-function),include!the output, and fail CI if a regenerated file differs. Large C APIs: a rawxyzzy-syscrate under a safexyzzycrate. C++:cxx.