Rust rules for writing, reviewing, and refactoring Rust code. Use when editing .rs files or Cargo.toml, fixing borrow-checker, lifetime, or Send errors, designing a crate's public API, writing async or unsafe code, or tuning performance.
Getting started
Full instructionsInstall the skill, then ask your AI tool for the task in plain words. The full SKILL.md below shows what it covers.
Instructions: SKILL.mdv1.0.2
Rust Skills
268 rules across 26 categories for idiomatic, safe, and fast Rust. Current for Rust 1.100 (2024 edition). This file is the index; each rule lives in rules/<id>.md next to it.
How to use
- Find the task in the table below. It names the categories to scan. A task that spans several rows uses all of them.
- In the index, read the summaries in those categories. Open the rule file for every rule that bears on the code in front of you.
- Apply the rules. When two rules pull in different directions, the higher-impact category wins: CRITICAL > HIGH > MEDIUM > LOW.
- When reviewing, report each finding with its rule id (for example
own-slice-over-vec) and the fix.
Done when every rule you opened is either applied or skipped for a stated reason.
If rules/ is not next to this file (a single-file install), fetch a rule from https://raw.githubusercontent.com/leonardomso/rust-skills/master/rules/<id>.md.
Task → categories
| Task | Categories |
|---|---|
| New function | own-, err-, name-, pat- |
| New struct or public API | api-, type-, trait-, conv-, doc- |
| Error handling | err-, api-, pat- |
| Borrow-checker or lifetime errors | own-, closure- |
| Async code | async-, own- |
| Threads, locks, atomics | conc-, own-, async- |
| Unsafe code or FFI | unsafe-, type-, test- |
| Conversions and parsing | conv-, api- |
| Serialization (serde) | serde-, type-, api- |
| Numeric / arithmetic | num-, type- |
| Macros / code generation | macro- |
| Closures / callbacks | closure-, type- |
| Collections | coll-, mem-, perf- |
| Logging / observability | obs-, err- |
| Tests and benchmarks | test-, perf- |
| Memory use | mem-, own-, perf- |
| Performance tuning | perf-, opt-, mem- |
| Cargo.toml, workspace, CI setup | proj-, lint-, opt-, perf-release-profile |
| Code review | every category the code touches, then anti- |
Index
1. Ownership & Borrowing (CRITICAL)
own-borrow-over-clone- Borrow with&Tand clone only to store, send across threads, or share viaArcown-slice-over-vec- Take&[T],&str, and&Pathin parameters, not&Vec<T>,&String, or&PathBufown-cow-conditional- UseCow<'a, T>for conditional ownershipown-arc-shared- UseArc<T>for thread-safe shared ownershipown-rc-single-thread- UseRc<T>for shared ownership in single-threaded contextsown-refcell-interior- UseRefCell<T>for interior mutability in single-threaded codeown-mutex-interior- UseMutex<T>for interior mutability across threadsown-rwlock-readers- UseRwLock<T>when reads significantly outnumber writesown-copy-small- ImplementCopyfor small, simple typesown-clone-explicit- Use explicitClonefor types where copying has meaningful costown-move-large- Move large types instead of copying; useBoxif moves are expensiveown-lifetime-elision- Rely on lifetime elision rules; add explicit lifetimes only when required
2. Error Handling (CRITICAL)
err-thiserror-lib- Usethiserrorfor library error typeserr-anyhow-app- Useanyhowfor application error handlingerr-result-over-panic- ReturnResult<T, E>for recoverable errors; panic only for bugs and unrecoverable stateerr-context-chain- Add context with.context()or.with_context()err-no-unwrap-prod- Propagate errors with?orexpecta documented invariant; keepunwrap()out of production pathserr-expect-bugs-only- Reserveexpect()for violated invariants that indicate bugs; returnResultfor user input, I/O, network, and database failureserr-question-mark- Use?operator for clean propagationerr-from-impl- ImplementFrom<E>for error conversions to enable?operatorerr-source-chain- Preserve error chains with#[source]orsource()methoderr-lowercase-msg- Start error messages lowercase, no trailing punctuationerr-custom-type- Define custom error types for domain-specific failures
3. Memory Optimization (CRITICAL)
mem-with-capacity- Usewith_capacity()when size is knownmem-smallvec- UseSmallVecfor usually-small collectionsmem-arrayvec- UseArrayVec<T, N>for fixed-capacity collections that never heap-allocatemem-box-large-variant- Box large enum variants to reduce overall enum sizemem-boxed-slice- UseBox<[T]>instead ofVec<T>for fixed-size heap datamem-thinvec- UseThinVec<T>for nullable collections with minimal overheadmem-clone-from- Useclone_from()to reuse allocations when repeatedly cloningmem-reuse-collections- Clear and reuse collections instead of creating new ones in loopsmem-avoid-format- Use string literals or&'static strwhere the text is fixed; reserveformat!()for text that variesmem-write-over-format- Write into a reused buffer withwrite!()instead of callingformat!()in loops and hot pathsmem-arena-allocator- Use arena allocators for batch allocationsmem-zero-copy- Use zero-copy patterns with slices andBytesmem-compact-string- Use compact string types for memory-constrained string storagemem-smaller-integers- Use appropriately-sized integers to reduce memory footprintmem-assert-type-size- Use static assertions to guard against accidental type size growthmem-take-replace- Usemem::take/mem::replaceto move a value out of a&mutwithout cloningmem-drop-order- Know and control drop order: struct fields drop top-to-bottom, locals in reversemem-allocator-api- Use the stableAllocatortrait withVec::new_inandBox::new_into control where a collection allocatesmem-global-allocator- For allocation-heavy applications, try a different global allocator and keep it only if benchmarks improvemem-shrink-to-fit- Callshrink_to_fit()on large, long-lived collections that were built by pushing
4. Unsafe Code (CRITICAL)
unsafe-safety-comment- Write a// SAFETY:comment above everyunsafeblock and a# Safetysection in everyunsafe fn.unsafe-minimize-scope- Keepunsafeblocks as small as possible — mark only the operation that requires unsafety, not the surrounding safe code.unsafe-miri-ci- Runcargo miri testin CI for every crate that containsunsafecode.unsafe-maybeuninit- UseMaybeUninit<T>for uninitialized memory; never usemem::uninitialized()ormem::zeroed()for types with validity invariants.unsafe-extern-block- In Rust 2024, wrapexternblocks inunsafe extern { }and annotate each item assafeorunsafe.unsafe-send-sync-manual- Document the invariants when manually implementingSendorSync; prefer letting the compiler derive them automatically.unsafe-no-mangle-unsafe- In Rust 2024, write#[unsafe(no_mangle)],#[unsafe(export_name = "...")], and#[unsafe(link_section = "...")]— not the bare attribute forms.unsafe-sound-abstractions- Keep every safe function sound: no input to it may cause undefined behavior. Mark functionsunsafeonly when the caller must uphold a UB-relevant invariant
5. API Design (HIGH)
api-builder-pattern- Use Builder pattern for complex constructionapi-builder-must-use- Mark builder methods with#[must_use]to prevent silent dropsapi-newtype-safety- Use newtypes to prevent mixing semantically different valuesapi-typestate- Use typestate pattern to encode state machine invariants in the type systemapi-sealed-trait- Use sealed traits to prevent external implementations while allowing useapi-extension-trait- Use extension traits to add methods to external typesapi-parse-dont-validate- Parse into validated types at boundariesapi-impl-into- Acceptimpl Into<T>for flexible APIs, implementFrom<T>for conversionsapi-impl-asref- UseAsRef<T>when you only need to borrow the inner dataapi-must-use- Mark types and functions with#[must_use]when ignoring results is likely a bugapi-non-exhaustive- Use#[non_exhaustive]on public enums and structs for forward compatibilityapi-from-not-into- ImplementFrom<T>, notInto<U>- From gives you Into for freeapi-default-impl- ImplementDefaultfor types with sensible default valuesapi-common-traits- Implement standard traits (Debug, Clone, PartialEq, etc.) for public typesapi-serde-optional- Make serde a feature flag, not a hard dependency for library cratesapi-impl-fromiterator- ImplementFromIteratorandExtendfor collection types, andIntoIteratorfor all three reference formsapi-operator-overload- Overload operators only when the semantics are natural and unsurprisingapi-avoid-statics- Pass correctness-relevant state explicitly instead of keeping it in a library'sstaticitemsapi-dont-leak-types- Preferstdtypes in public APIs; expose third-party types only when they give a clear benefitapi-impl-rangebounds- Acceptimpl RangeBounds<T>for range parameters instead of separate bounds or a concreteRangeapi-no-glob-reexports- Re-export items one by one, not withpub use module::*api-sans-io- Takeimpl Read/impl Write(or their async counterparts) instead of files or paths for one-shot I/Oapi-types-send- Make public types and the futures they produceSend, and assert it so it stays that way
6. Async/Await (HIGH)
async-tokio-runtime- Configure Tokio runtime appropriately for your workloadasync-no-lock-await- ReleaseMutex/RwLockguards before.await: take what you need, drop the lock, do the async work, then lock briefly to write backasync-spawn-blocking- Usespawn_blockingfor CPU-intensive workasync-tokio-fs- Usetokio::fsinstead ofstd::fsin async codeasync-cancellation-token- UseCancellationTokenfor graceful shutdown and task cancellationasync-join-parallel- Usejoin!ortry_join!for concurrent independent futuresasync-try-join- Usetry_join!for concurrent fallible operations with early return on errorasync-select-racing- Useselect!to race futures and handle the first to completeasync-bounded-channel- Use bounded channels to apply backpressure and prevent unbounded memory growthasync-mpsc-queue- Usempscchannels for async message queues between tasksasync-broadcast-pubsub- Usebroadcastchannel for pub/sub where all subscribers receive all messagesasync-watch-latest- Usewatchchannel for sharing the latest value with multiple observersasync-oneshot-response- Useoneshotchannel for request-response patternsasync-joinset-structured- UseJoinSetfor managing dynamic collections of spawned tasksasync-clone-before-await- Clone theArchandle, not its contents, before moving it into a spawned task; keep owned handles across.awaitand borrow after itasync-fn-in-trait- Use nativeasync fnin traits (stable 1.75) instead of theasync_traitmacroasync-async-fn-bounds- UseAsyncFn/AsyncFnMut/AsyncFnOncebounds instead ofF: Fn() -> Fut, Fut: Futureasync-cancel-safety- Ensure futures used intokio::select!branches are cancellation-safeasync-future-size- Track the size of futures on hot paths and keep large values out of their state machinesasync-yield-points- Addyield_now().awaitpoints to long CPU-bound loops in async code so they do not starve other tasks
7. Concurrency (HIGH)
conc-rayon-par-iter- Use rayon'spar_iter()for CPU-bound data parallelismconc-scoped-threads- Usestd::thread::scopeto borrow stack data across threadsconc-atomic-ordering- Use the weakest correct memoryOrderingfor every atomic operationconc-thread-local- Preferthread_local!withCell/RefCelloverstatic mut
8. Compiler Optimization (HIGH)
opt-inline-small- Use#[inline]for small hot functionsopt-inline-always-rare- Use#[inline(always)]sparingly—only for critical hot paths proven by profilingopt-inline-never-cold- Move error, panic, and fallback paths into#[cold]#[inline(never)]functions so hot code stays smallopt-likely-hint- Use code structure to hint at likely branches; use intrinsics on nightlyopt-lto-release- Enable LTO in release buildsopt-codegen-units- Setcodegen-units = 1for maximum optimization in release buildsopt-pgo-profile- Use Profile-Guided Optimization (PGO) for maximum performanceopt-target-cpu- Usetarget-cpu=nativefor maximum performance on known deployment targetsopt-bounds-check- Use iterators and patterns that eliminate bounds checks in hot pathsopt-simd-portable- Use portable SIMD for vectorized operations across architecturesopt-cache-friendly- Organize data for cache-efficient access patterns
9. Numeric & Arithmetic Safety (HIGH)
num-overflow-explicit- Handle integer overflow explicitly:checked_/saturating_/wrapping_/overflowing_num-cast-try-from- Convert numbers withFromfor widening andTryFromfor narrowing; keepasfor casts you know are lossless or intentionally truncatingnum-float-compare- Compare floats with a tolerance and order them withtotal_cmp;==on computed floats is almost always wrongnum-saturating-clamp- Bound values withclampand saturating arithmeticnum-nonzero- UseNonZero*types to forbid zero and unlock the niche optimization
10. Type Safety (MEDIUM)
type-newtype-ids- Wrap IDs in newtypes:UserId(u64)type-newtype-validated- Use newtypes to enforce validation at construction timetype-enum-states- Use enums for mutually exclusive statestype-option-nullable- UseOption<T>for values that might not existtype-result-fallible- UseResult<T, E>for operations that can failtype-phantom-marker- UsePhantomDatato express type relationships without runtime costtype-never-diverge- Use!(never type) for functions that never returntype-generic-bounds- Add trait bounds only where needed, prefer where clauses for readabilitytype-no-stringly- Model fixed value sets as enums and semantic values as validated newtypes, and parse strings once at the boundarytype-repr-transparent- Use#[repr(transparent)]for newtypes in FFI contextstype-deref-coercion- ImplementDeref/DerefMutonly for smart-pointer and transparent wrapper typestype-display-vs-debug- UseDisplayfor user-facing output andDebugfor diagnostics; never swap themtype-numeric-fmt- ImplementLowerHex,UpperHex,Octal, andBinaryfor numeric newtypes
11. Trait & Generics Design (MEDIUM)
trait-associated-type-vs-generic- Use an associated type when each impl has exactly one output type; use a generic parameter when a type can implement the trait for many input typestrait-blanket-impl- Use a blanket implimpl<T: Bound> Trait for Tto give behaviour to every type that satisfies a boundtrait-coherence-newtype- Respect the orphan rule; wrap a foreign type in a newtype to implement a foreign trait on ittrait-default-methods- Define a trait in terms of a few required methods plus defaulted ones built on top of themtrait-dyn-vs-generic- Default to generics andimpl Trait; usedyn Traitonly for mixed types, runtime choice, or plug-instrait-object-safety- Keep a trait dyn-compatible (object-safe) when you needdyn Trait
12. Conversions (MEDIUM)
conv-tryfrom-fallible- ImplementTryFromfor fallible conversions instead of ad-hoc conversion functionsconv-fromstr-parsing- ImplementFromStrto enablestr::parsefor string-to-type conversionsconv-asmut-mutable- Acceptimpl AsMut<T>for flexible mutable borrowed inputs instead of concrete mutable references
13. Const & Compile-Time (MEDIUM)
const-block- Use inlineconst { }blocks for compile-time evaluation and assertionsconst-fn- Make functionsconst fnwhen they can run at compile timeconst-generics- Parameterize over values with const generics<const N: usize>const-vs-static- Useconstfor an inlined value andstaticfor a single addressed instance
14. Serde (MEDIUM)
serde-rename-all- Match the external naming convention with#[serde(rename_all = ...)]serde-default-compat- Use#[serde(default)]for optional and backward-compatible fieldsserde-skip-empty- Omit empty fields withskip_serializing_ifserde-flatten- Inline nested structs or capture extra keys with#[serde(flatten)]serde-enum-representation- Choose enum tagging deliberately: externally, internally, adjacently tagged, or untaggedserde-deny-unknown-fields- Reject unexpected keys with#[serde(deny_unknown_fields)]serde-custom-with- Customize a field's (de)serialization withwith/serialize_with/deserialize_withserde-try-from-validate- Validate while deserializing with#[serde(try_from = "Raw")]
15. Pattern Matching (MEDIUM)
pat-let-else- Uselet ... elsefor early-return pattern extractionpat-matches-macro- Usematches!()for boolean pattern testspat-if-let-chains- Useif letchains to combine pattern bindings and conditionspat-exhaustive-enum- Match owned enums exhaustively; avoid catch-all_that hides new variantspat-at-bindings- Use@bindings to capture a value while matching it against a pattern
16. Macros (MEDIUM)
macro-prefer-functions- Reach for a macro only when a function or generic cannot express itmacro-rules-hygiene- Rely onmacro_rules!hygiene and use$cratefor paths to your crate's itemsmacro-fragment-specifiers- Capture with precise fragment specifiers, not raw:tt, where you canmacro-export-crate-path- Export declarative macros with#[macro_export]and a clean import pathmacro-private-helpers- Hide macro-generated helper items behind a#[doc(hidden)] pub mod __privatemacro-proc-two-crate- Put procedural macros in a dedicatedproc-macro = truecrate and re-export from the facademacro-proc-syn-quote- Build procedural macros withsyn,quote, andproc-macro2macro-proc-error-spans- Report proc-macro errors as spanned compile errors, never by panickingmacro-cfg-select- Usecfg_select!(stable since Rust 1.95) to pick one compile-time branch instead of stacked#[cfg]or thecfg-ifcratemacro-pin-impl-crate- Pin a companion proc-macro crate to your crate's exact version with=x.y.z
17. Closures (MEDIUM)
closure-fn-trait-bounds- Require the least restrictiveFntrait a callback needs (FnOnce⊇FnMut⊇Fn)closure-impl-fn-return- Return closures asimpl Fn/FnMut/FnOnce, notBox<dyn Fn>closure-move-capture- Usemovefor closures that outlive the current scope; clone beforemoveto keep the originalclosure-static-vs-dyn- Acceptimpl Fn(generic) for hot callbacks; use&dyn Fn/Box<dyn Fn>to cut code size or to store themclosure-disjoint-capture- Capture only what you use; lean on edition-2021 disjoint closure captures
18. Collections (MEDIUM)
coll-binaryheap- UseBinaryHeapfor a priority queue or repeated max-extractioncoll-map-choice- Pick the map by access pattern:HashMap(fast, unordered),BTreeMap(sorted / range queries),IndexMap(insertion order)coll-seq-choice- Default toVec; useVecDequefor queue/deque behaviour; avoidLinkedListcoll-set-membership- UseHashSet/BTreeSetfor membership tests and dedup, not linearVec::contains
19. Naming Conventions (MEDIUM)
name-types-camel- UseUpperCamelCasefor types, traits, and enum namesname-variants-camel- UseUpperCamelCasefor enum variantsname-funcs-snake- Usesnake_casefor functions, methods, variables, and modulesname-consts-screaming- UseSCREAMING_SNAKE_CASEfor constants and staticsname-lifetime-short- Use short, conventional lifetime names:'a,'b,'de,'srcname-type-param-single- Use single uppercase letters for type parameters:T,E,K,Vname-as-free- Use theas_prefix for free, borrowed-to-borrowed conversionsname-to-expensive- Useto_prefix for expensive conversions that allocate or computename-into-ownership- Useinto_prefix for ownership-consuming conversionsname-no-get-prefix- Omit get_ prefix for simple gettersname-is-has-bool- Useis_,has_,can_,should_prefixes for boolean-returning methodsname-iter-method- Name iterator methodsiter(),iter_mut(), andinto_iter(), and implementIntoIteratorfor owned,&, and&mutname-iter-type-match- Name iterator types after their source methodname-acronym-word- Treat acronyms as words in identifiers:HttpServer, notHTTPServername-crate-no-rs- Name crates for what they do, without a-rsor-rustsuffixname-weasel-words- Name types for what they do; replaceService,Manager,Factory, and similar empty words with a specific noun
20. Testing (MEDIUM)
test-cfg-test-module- Put unit tests in#[cfg(test)] mod tests { }within each moduletest-use-super- Useuse super::*;in test modules to access parent module itemstest-integration-dir- Put integration tests in thetests/directorytest-descriptive-names- Use descriptive test names that explain what is being testedtest-arrange-act-assert- Structure tests with clear Arrange, Act, Assert sectionstest-proptest-properties- Use proptest for property-based testingtest-mockall-mocking- Use mockall for trait mockingtest-mock-traits- Use traits for dependencies to enable mocking in teststest-fixture-raii- Use RAII pattern (Drop trait) for automatic test cleanuptest-tokio-async- Use#[tokio::test]for async teststest-should-panic- Use#[should_panic]to test that code panics as expectedtest-criterion-bench- Usecriterionfor benchmarkingtest-doctest-examples- Keep documentation examples as executable docteststest-loom-concurrency- Useloomto exhaustively test lock-free and concurrent codetest-snapshot-testing- Use snapshot testing (insta) for complex or serialized outputtest-no-tautological- Test properties and independently known values, not a restatement of the code under testtest-utils-feature-gated- Put mocks, fake data, and safety-check overrides behind atest-utilfeature
21. Documentation (MEDIUM)
doc-all-public- Document all public items with///doc commentsdoc-module-inner- Use//!for module-level documentationdoc-examples-section- Include# Exampleswith runnable codedoc-errors-section- Give every fallible public function an# Errorssection that lists each failure condition and links the error variantsdoc-panics-section- Include# Panicssection for functions that can panicdoc-safety-section- Include# Safetysection for unsafe functionsdoc-question-mark- Use?in examples, not.unwrap()doc-hidden-setup- Use#prefix to hide example setup codedoc-intra-links- Link types, methods, and modules in doc comments with intra-doc links such as [Type] and [Self::method]doc-cargo-metadata- FillCargo.tomlmetadata for published cratesdoc-crate-readme- Unify the README and crate root docs with#![doc = include_str!("../README.md")]doc-alias-suggestions- Add#[doc(alias = "...")]so users and rustc find an item under the name they expectdoc-first-sentence- Make the first sentence of a doc comment a short, one-line summary of about 15 words or fewer
22. Observability (MEDIUM)
obs-tracing-over-log- Usetracingfor structured, span-aware diagnostics instead ofprintln!or barelogobs-library-facade- Libraries emit through the tracing/log facade and never install a subscriberobs-structured-fields- Record structured key-value fields, not values interpolated into the message stringobs-instrument-spans- Use#[tracing::instrument]and spans to attach context to async tasks and requestsobs-levels-filter- Use log levels meaningfully and filter withEnvFilter/RUST_LOGobs-error-chain- Log errors with their full source chain, and log each error exactly onceobs-no-sensitive-data- Redact or skip secrets and PII before they reach a log; never log them rawobs-log-overhead- Keep telemetry on hot paths cheap: no allocation per event and no per-item events in inner loops
23. Performance Patterns (MEDIUM)
perf-iter-over-index- Iterate withiter(),iter_mut(),zipand adapters instead of indexing in a0..lenloopperf-iter-lazy- Keep iterators lazy, collect only when neededperf-collect-once- Chain iterator adapters and collect once at the end, or not at allperf-entry-api- Use entry API for map insert-or-updateperf-drain-reuse- Use drain to reuse allocationsperf-extend-batch- Use extend for batch insertionsperf-chain-avoid- Use a single iterator or an explicit loop in hot loops;chainadds a branch per itemperf-collect-into- Use collect_into for reusing containersperf-black-box-bench- Use black_box in benchmarksperf-release-profile- Optimize release profile settingsperf-profile-first- Profile under a realistic workload, then optimize only the measured hot spotperf-ahash- Use a faster hasher (ahash/FxHashMap) when DoS resistance is not neededperf-io-buffering- WrapRead/WriteinBufReader/BufWriterfor many small operations
24. Project Structure (LOW)
proj-lib-main-split- Keepmain.rsminimal, logic inlib.rsproj-mod-by-feature- Organize modules by feature, not typeproj-flat-small- Keep small projects flatproj-mod-rs-dir- Use mod.rs for multi-file modulesproj-pub-crate-internal- Use pub(crate) for internal APIsproj-pub-super-parent- Use pub(super) for parent-only visibilityproj-pub-use-reexport- Use pub use for clean public APIproj-prelude-module- Create prelude module for common importsproj-bin-dir- Put multiple binaries in src/bin/proj-workspace-large- Use workspaces for large projectsproj-workspace-deps- Use workspace dependency inheritance for consistent versions across cratesproj-feature-additive- Design Cargo features to be strictly additiveproj-msrv-declare- Declarerust-version(MSRV) in Cargo.toml and test it in CIproj-build-rs-minimal- Keepbuild.rsminimal, deterministic, and idempotentproj-dependency-cooldown- Set a minimum publish age so the resolver skips brand-new dependency versions
25. Clippy & Linting (LOW)
lint-pedantic-selective- Enable clippy::pedantic selectivelylint-missing-docs- Warn on missing documentation for public itemslint-unsafe-doc- Require documentation for unsafe blockslint-cargo-metadata- Enable clippy::cargo for published crateslint-rustfmt-check- Run cargo fmt --check in CIlint-workspace-lints- Configure lints at workspace level for consistent enforcementlint-cfg-check- Enableunexpected_cfgsand declare known cfgs to catch feature-gate typoslint-clippy-nursery-selected- Enable high-valueclippy::nurserylints selectively, not the whole grouplint-build-warnings- Deny warnings in CI withbuild.warningsinstead ofRUSTFLAGS=-Dwarningslint-cargo-lints- Configure Cargo's own lints in[lints.cargo]and deny unused dependencieslint-expect-over-allow- Use#[expect(lint, reason = "...")]instead of#[allow]when overriding a lint for one itemlint-clippy-groups- Keep clippy's default groups on —correctnessat deny;suspicious,style,complexity, andperfat warn — set them once in[lints.clippy], and fail CI on their warnings
26. Anti-patterns (REFERENCE)
anti-empty-catch- Handle, propagate, or log every error; make an intentional discard explicit and commentedanti-over-abstraction- Start concrete; add generics or traits when a second real use case appears
Common mistakes and the rule that fixes each:
| Symptom | Fix |
|---|---|
.unwrap() in production code |
err-no-unwrap-prod |
expect() on a recoverable error |
err-expect-bugs-only |
| Panicking on expected failures | err-result-over-panic |
.clone() to quiet the borrow checker |
own-borrow-over-clone |
&String / &Vec<T> parameters |
own-slice-over-vec |
A lock guard held across .await |
async-no-lock-await |
| Index loops where an iterator fits | perf-iter-over-index |
| Collecting between iterator steps | perf-collect-once |
format! in a hot path |
mem-write-over-format, mem-avoid-format |
| Optimizing without a profile | perf-profile-first |
| Strings where an enum or newtype fits | type-no-stringly |
Box<dyn Trait> where impl Trait works |
trait-dyn-vs-generic |
Explore more skills
Browse all- Senior FrontendBuild and review React, Next.js, TypeScript or Tailwind frontends: components, scaffolding, performance and bundle…
- UI Design SystemUse when building a design system: tokens, component docs, responsive scales or developer handoff. Generates tokens…
- Founder ConsumerThe consumer panel. Spins up a swarm of buyer sub-agents (default 100, --quick for 20) trained on the user's target…
- Frontend DesignGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with…
- Senior BackendBuild and fix backend services: REST or GraphQL APIs, auth, microservices, PostgreSQL queries, migrations and load…
- Self Improving AgentCurate what the agent has learned into durable project knowledge. Reviews Claude Code auto-memory (MEMORY.md and its…
Security
Reviews (0)
Frequently asked questions about rust-skills
What does the rust-skills skill do?
Rust rules for writing, reviewing, and refactoring Rust code. Use when editing .rs files or Cargo.toml, fixing borrow-checker, lifetime, or Send errors, designing a crate's public API, writing async or unsafe code, or tuning performance. It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.
How do I install the rust-skills skill?
Run `npx @skills-hub-ai/cli install rust-skills` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/rust-skills/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.
Which AI tools does rust-skills work with?
rust-skills runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.
Is the rust-skills skill free?
Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.
How do I use rust-skills after installing it?
In Claude Code, type `/rust-skills` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.
Can I share the rust-skills skill with my team?
Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.
Badge for your README
Show that this skill is on Skills Hub. The badge links back to this page and shows the live install count.
[](https://skills-hub.ai/skills/rust-skills)<a href="https://skills-hub.ai/skills/rust-skills"><img src="https://skills-hub.ai/api/badges/skill/rust-skills" alt="Install on Skills Hub"></a>More options in the badge docs.