Loading...
Loading...
Comprehensive Rust coding guidelines covering ownership, error handling, async patterns, traits, testing, performance, clippy, and documentation. Use when writing new Rust code, reviewing or refactoring existing Rust, implementing async systems with Tokio, designing error hierarchies, choosing between borrowing and cloning, setting up tests or benchmarks, configuring linting, or optimizing performance. Do not use for non-Rust languages or general software architecture unrelated to Rust idioms.
npx skill4agent add pedronauck/skills rust-best-practices| Topic | Reference | Load When |
|---|---|---|
| Coding Style | | Naming, imports, iterators, comments, string handling, macros |
| Error Handling | | Result, Option, ?, thiserror, anyhow, custom errors, async errors |
| Ownership & Pointers | | Lifetimes, borrowing, smart pointers, Pin, Cow, interior mutability |
| Traits & Generics | | Trait design, dispatch, GATs, sealed traits, type state pattern |
| Async & Concurrency | | Tokio, channels, streams, shutdown, runtime config, async traits |
| Sync Concurrency | | Atomics, Mutex, RwLock, lock ordering, Send/Sync, memory ordering |
| Testing | | Unit/integration/doc tests, snapshot, proptest, mockall, benchmarks, fuzz |
| Performance | | Profiling, flamegraph, cloning, stack vs heap, iterators, allocation |
| Clippy & Linting | | Clippy config, key lints, workspace setup, #[expect] vs #[allow] |
| Documentation | | Doc comments, rustdoc, doc lints, coverage checklist |
&T.clone()&strString&[T]Vec<T>get_fn name()fn get_name()as_to_into_iter()iter_mut()into_iter()stdsuper::crate::format!+s.bytes()s.chars()Result<T, E>panic!unwrap()expect()?if letlet...elsethiserroranyhow?match_elseok_or_elseunwrap_or_elseinspect_errmap_errassert!CopyCopyCow<'_, T>'src'ctx'conn'atry_borrow()RefCell.borrow_mut()let x = x.parse()?| Pointer | When to Use |
|---|---|
| Single ownership, heap allocation, recursive types |
| Shared ownership, single-threaded |
| Shared ownership, multi-threaded |
| Interior mutability, single-threaded |
| Interior mutability, multi-threaded |
dyn TraitSelf: Sized&self&mut selfselfstruct Connection<S> { _state: PhantomData<S> }
struct Disconnected;
struct Connected;
impl Connection<Connected> { fn send(&self, data: &[u8]) { /* ... */ } }.awaitstd::thread::sleeptokio::time::sleepSendJoinSetCancellationTokentokio_utiltracing#[instrument]| Channel | Use Case |
|---|---|
| Multi-producer, single-consumer message passing |
| Multi-producer, multi-consumer event fan-out |
| Single value, single use (request-response) |
| Latest-value-only, change notification |
crossbeam::channelstd::sync::mpsctokio::sync::{mpsc, broadcast, oneshot, watch}AtomicBoolAtomicUsizeMutexRelaxedAcquireReleaseSeqCstprocess_should_return_error_when_input_empty()mod///cargo test --doccargo insta testcargo insta reviewrstest#[case::name]proptestmockall#[automock]criterioniter_batchedBenchmarkIdcargo-fuzzlibfuzzer_syscargo-tarpaulincargo-llvm-covsqlx::test#[should_panic]#[ignore]--releasecargo clippy -- -D clippy::perfcargo flamegraphsamplyVec::with_capacity()String::with_capacity()for.collect()smallvecCow<'_, T>s.bytes()s.chars()cargo clippy --all-targets --all-features --locked -- -D warnings| Lint | Catches |
|---|---|
| Unnecessary |
| Unnecessary |
| Oversized variants (consider |
| Premature |
| |
| Functions always returning |
| |
#[expect(clippy::lint)]#[allow(...)]expect#![warn(clippy::all)]Cargo.toml///////!lib.rsmod.rsTODO// TODO(#42): description#![deny(missing_docs)]# Examples# Errors# Panics# Safety| Doc Lint | Purpose |
|---|---|
| Ensure all public items documented |
| Catch dead cross-references |
| Document panic conditions |
| Document error conditions |
| Document unsafe safety requirements |
struct Email(String)if let [first, .., last] = sliceVeclet x = x.parse()?Cow<str>contains()| Deprecated | Better | Since |
|---|---|---|
| | Rust 1.70 |
| | Rust 1.80 |
| | — |
| | — |
| | — |
| | Rust 2018 |
| Native | Rust 1.75 |
[dependencies]
thiserror = "2"
anyhow = "1"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
tracing = "0.1"
tracing-subscriber = "0.3"
[dev-dependencies]
rstest = "0.25"
proptest = "1"
mockall = "0.13"
criterion = { version = "0.5", features = ["html_reports"] }
insta = { version = "1", features = ["yaml"] }Cargo.toml[workspace.lints.clippy]
all = { level = "warn", priority = -1 }
pedantic = { level = "warn", priority = -1 }rustfmt.tomlreorder_imports = true
imports_granularity = "Crate"
group_imports = "StdExternalCrate"ResultOptionthiserroranyhowunsafeunsafecargo clippycargo fmt///tracingrstestproptestinstamockallcriterionunwrap()unsafe#[expect(...)].awaitstd::thread::sleeppanic!String&strspawn_blocking