Skip to main content

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.

  • 17 installs
  • v1.0.2
  • Reviewed Jul 21
  • No reviews yet

Getting started

Full instructions

Install 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

  1. Find the task in the table below. It names the categories to scan. A task that spans several rows uses all of them.
  2. 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.
  3. Apply the rules. When two rules pull in different directions, the higher-impact category wins: CRITICAL > HIGH > MEDIUM > LOW.
  4. 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 &T and clone only to store, send across threads, or share via Arc
  • own-slice-over-vec - Take &[T], &str, and &Path in parameters, not &Vec<T>, &String, or &PathBuf
  • own-cow-conditional - Use Cow<'a, T> for conditional ownership
  • own-arc-shared - Use Arc<T> for thread-safe shared ownership
  • own-rc-single-thread - Use Rc<T> for shared ownership in single-threaded contexts
  • own-refcell-interior - Use RefCell<T> for interior mutability in single-threaded code
  • own-mutex-interior - Use Mutex<T> for interior mutability across threads
  • own-rwlock-readers - Use RwLock<T> when reads significantly outnumber writes
  • own-copy-small - Implement Copy for small, simple types
  • own-clone-explicit - Use explicit Clone for types where copying has meaningful cost
  • own-move-large - Move large types instead of copying; use Box if moves are expensive
  • own-lifetime-elision - Rely on lifetime elision rules; add explicit lifetimes only when required

2. Error Handling (CRITICAL)

  • err-thiserror-lib - Use thiserror for library error types
  • err-anyhow-app - Use anyhow for application error handling
  • err-result-over-panic - Return Result<T, E> for recoverable errors; panic only for bugs and unrecoverable state
  • err-context-chain - Add context with .context() or .with_context()
  • err-no-unwrap-prod - Propagate errors with ? or expect a documented invariant; keep unwrap() out of production paths
  • err-expect-bugs-only - Reserve expect() for violated invariants that indicate bugs; return Result for user input, I/O, network, and database failures
  • err-question-mark - Use ? operator for clean propagation
  • err-from-impl - Implement From<E> for error conversions to enable ? operator
  • err-source-chain - Preserve error chains with #[source] or source() method
  • err-lowercase-msg - Start error messages lowercase, no trailing punctuation
  • err-custom-type - Define custom error types for domain-specific failures

3. Memory Optimization (CRITICAL)

  • mem-with-capacity - Use with_capacity() when size is known
  • mem-smallvec - Use SmallVec for usually-small collections
  • mem-arrayvec - Use ArrayVec<T, N> for fixed-capacity collections that never heap-allocate
  • mem-box-large-variant - Box large enum variants to reduce overall enum size
  • mem-boxed-slice - Use Box<[T]> instead of Vec<T> for fixed-size heap data
  • mem-thinvec - Use ThinVec<T> for nullable collections with minimal overhead
  • mem-clone-from - Use clone_from() to reuse allocations when repeatedly cloning
  • mem-reuse-collections - Clear and reuse collections instead of creating new ones in loops
  • mem-avoid-format - Use string literals or &'static str where the text is fixed; reserve format!() for text that varies
  • mem-write-over-format - Write into a reused buffer with write!() instead of calling format!() in loops and hot paths
  • mem-arena-allocator - Use arena allocators for batch allocations
  • mem-zero-copy - Use zero-copy patterns with slices and Bytes
  • mem-compact-string - Use compact string types for memory-constrained string storage
  • mem-smaller-integers - Use appropriately-sized integers to reduce memory footprint
  • mem-assert-type-size - Use static assertions to guard against accidental type size growth
  • mem-take-replace - Use mem::take / mem::replace to move a value out of a &mut without cloning
  • mem-drop-order - Know and control drop order: struct fields drop top-to-bottom, locals in reverse
  • mem-allocator-api - Use the stable Allocator trait with Vec::new_in and Box::new_in to control where a collection allocates
  • mem-global-allocator - For allocation-heavy applications, try a different global allocator and keep it only if benchmarks improve
  • mem-shrink-to-fit - Call shrink_to_fit() on large, long-lived collections that were built by pushing

4. Unsafe Code (CRITICAL)

  • unsafe-safety-comment - Write a // SAFETY: comment above every unsafe block and a # Safety section in every unsafe fn.
  • unsafe-minimize-scope - Keep unsafe blocks as small as possible — mark only the operation that requires unsafety, not the surrounding safe code.
  • unsafe-miri-ci - Run cargo miri test in CI for every crate that contains unsafe code.
  • unsafe-maybeuninit - Use MaybeUninit<T> for uninitialized memory; never use mem::uninitialized() or mem::zeroed() for types with validity invariants.
  • unsafe-extern-block - In Rust 2024, wrap extern blocks in unsafe extern { } and annotate each item as safe or unsafe.
  • unsafe-send-sync-manual - Document the invariants when manually implementing Send or Sync; 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 functions unsafe only when the caller must uphold a UB-relevant invariant

5. API Design (HIGH)

  • api-builder-pattern - Use Builder pattern for complex construction
  • api-builder-must-use - Mark builder methods with #[must_use] to prevent silent drops
  • api-newtype-safety - Use newtypes to prevent mixing semantically different values
  • api-typestate - Use typestate pattern to encode state machine invariants in the type system
  • api-sealed-trait - Use sealed traits to prevent external implementations while allowing use
  • api-extension-trait - Use extension traits to add methods to external types
  • api-parse-dont-validate - Parse into validated types at boundaries
  • api-impl-into - Accept impl Into<T> for flexible APIs, implement From<T> for conversions
  • api-impl-asref - Use AsRef<T> when you only need to borrow the inner data
  • api-must-use - Mark types and functions with #[must_use] when ignoring results is likely a bug
  • api-non-exhaustive - Use #[non_exhaustive] on public enums and structs for forward compatibility
  • api-from-not-into - Implement From<T>, not Into<U> - From gives you Into for free
  • api-default-impl - Implement Default for types with sensible default values
  • api-common-traits - Implement standard traits (Debug, Clone, PartialEq, etc.) for public types
  • api-serde-optional - Make serde a feature flag, not a hard dependency for library crates
  • api-impl-fromiterator - Implement FromIterator and Extend for collection types, and IntoIterator for all three reference forms
  • api-operator-overload - Overload operators only when the semantics are natural and unsurprising
  • api-avoid-statics - Pass correctness-relevant state explicitly instead of keeping it in a library's static items
  • api-dont-leak-types - Prefer std types in public APIs; expose third-party types only when they give a clear benefit
  • api-impl-rangebounds - Accept impl RangeBounds<T> for range parameters instead of separate bounds or a concrete Range
  • api-no-glob-reexports - Re-export items one by one, not with pub use module::*
  • api-sans-io - Take impl Read/impl Write (or their async counterparts) instead of files or paths for one-shot I/O
  • api-types-send - Make public types and the futures they produce Send, and assert it so it stays that way

6. Async/Await (HIGH)

  • async-tokio-runtime - Configure Tokio runtime appropriately for your workload
  • async-no-lock-await - Release Mutex/RwLock guards before .await: take what you need, drop the lock, do the async work, then lock briefly to write back
  • async-spawn-blocking - Use spawn_blocking for CPU-intensive work
  • async-tokio-fs - Use tokio::fs instead of std::fs in async code
  • async-cancellation-token - Use CancellationToken for graceful shutdown and task cancellation
  • async-join-parallel - Use join! or try_join! for concurrent independent futures
  • async-try-join - Use try_join! for concurrent fallible operations with early return on error
  • async-select-racing - Use select! to race futures and handle the first to complete
  • async-bounded-channel - Use bounded channels to apply backpressure and prevent unbounded memory growth
  • async-mpsc-queue - Use mpsc channels for async message queues between tasks
  • async-broadcast-pubsub - Use broadcast channel for pub/sub where all subscribers receive all messages
  • async-watch-latest - Use watch channel for sharing the latest value with multiple observers
  • async-oneshot-response - Use oneshot channel for request-response patterns
  • async-joinset-structured - Use JoinSet for managing dynamic collections of spawned tasks
  • async-clone-before-await - Clone the Arc handle, not its contents, before moving it into a spawned task; keep owned handles across .await and borrow after it
  • async-fn-in-trait - Use native async fn in traits (stable 1.75) instead of the async_trait macro
  • async-async-fn-bounds - Use AsyncFn/AsyncFnMut/AsyncFnOnce bounds instead of F: Fn() -> Fut, Fut: Future
  • async-cancel-safety - Ensure futures used in tokio::select! branches are cancellation-safe
  • async-future-size - Track the size of futures on hot paths and keep large values out of their state machines
  • async-yield-points - Add yield_now().await points to long CPU-bound loops in async code so they do not starve other tasks

7. Concurrency (HIGH)

  • conc-rayon-par-iter - Use rayon's par_iter() for CPU-bound data parallelism
  • conc-scoped-threads - Use std::thread::scope to borrow stack data across threads
  • conc-atomic-ordering - Use the weakest correct memory Ordering for every atomic operation
  • conc-thread-local - Prefer thread_local! with Cell/RefCell over static mut

8. Compiler Optimization (HIGH)

  • opt-inline-small - Use #[inline] for small hot functions
  • opt-inline-always-rare - Use #[inline(always)] sparingly—only for critical hot paths proven by profiling
  • opt-inline-never-cold - Move error, panic, and fallback paths into #[cold] #[inline(never)] functions so hot code stays small
  • opt-likely-hint - Use code structure to hint at likely branches; use intrinsics on nightly
  • opt-lto-release - Enable LTO in release builds
  • opt-codegen-units - Set codegen-units = 1 for maximum optimization in release builds
  • opt-pgo-profile - Use Profile-Guided Optimization (PGO) for maximum performance
  • opt-target-cpu - Use target-cpu=native for maximum performance on known deployment targets
  • opt-bounds-check - Use iterators and patterns that eliminate bounds checks in hot paths
  • opt-simd-portable - Use portable SIMD for vectorized operations across architectures
  • opt-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 with From for widening and TryFrom for narrowing; keep as for casts you know are lossless or intentionally truncating
  • num-float-compare - Compare floats with a tolerance and order them with total_cmp; == on computed floats is almost always wrong
  • num-saturating-clamp - Bound values with clamp and saturating arithmetic
  • num-nonzero - Use NonZero* 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 time
  • type-enum-states - Use enums for mutually exclusive states
  • type-option-nullable - Use Option<T> for values that might not exist
  • type-result-fallible - Use Result<T, E> for operations that can fail
  • type-phantom-marker - Use PhantomData to express type relationships without runtime cost
  • type-never-diverge - Use ! (never type) for functions that never return
  • type-generic-bounds - Add trait bounds only where needed, prefer where clauses for readability
  • type-no-stringly - Model fixed value sets as enums and semantic values as validated newtypes, and parse strings once at the boundary
  • type-repr-transparent - Use #[repr(transparent)] for newtypes in FFI contexts
  • type-deref-coercion - Implement Deref/DerefMut only for smart-pointer and transparent wrapper types
  • type-display-vs-debug - Use Display for user-facing output and Debug for diagnostics; never swap them
  • type-numeric-fmt - Implement LowerHex, UpperHex, Octal, and Binary for 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 types
  • trait-blanket-impl - Use a blanket impl impl<T: Bound> Trait for T to give behaviour to every type that satisfies a bound
  • trait-coherence-newtype - Respect the orphan rule; wrap a foreign type in a newtype to implement a foreign trait on it
  • trait-default-methods - Define a trait in terms of a few required methods plus defaulted ones built on top of them
  • trait-dyn-vs-generic - Default to generics and impl Trait; use dyn Trait only for mixed types, runtime choice, or plug-ins
  • trait-object-safety - Keep a trait dyn-compatible (object-safe) when you need dyn Trait

12. Conversions (MEDIUM)

  • conv-tryfrom-fallible - Implement TryFrom for fallible conversions instead of ad-hoc conversion functions
  • conv-fromstr-parsing - Implement FromStr to enable str::parse for string-to-type conversions
  • conv-asmut-mutable - Accept impl AsMut<T> for flexible mutable borrowed inputs instead of concrete mutable references

13. Const & Compile-Time (MEDIUM)

  • const-block - Use inline const { } blocks for compile-time evaluation and assertions
  • const-fn - Make functions const fn when they can run at compile time
  • const-generics - Parameterize over values with const generics <const N: usize>
  • const-vs-static - Use const for an inlined value and static for 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 fields
  • serde-skip-empty - Omit empty fields with skip_serializing_if
  • serde-flatten - Inline nested structs or capture extra keys with #[serde(flatten)]
  • serde-enum-representation - Choose enum tagging deliberately: externally, internally, adjacently tagged, or untagged
  • serde-deny-unknown-fields - Reject unexpected keys with #[serde(deny_unknown_fields)]
  • serde-custom-with - Customize a field's (de)serialization with with / serialize_with / deserialize_with
  • serde-try-from-validate - Validate while deserializing with #[serde(try_from = "Raw")]

15. Pattern Matching (MEDIUM)

  • pat-let-else - Use let ... else for early-return pattern extraction
  • pat-matches-macro - Use matches!() for boolean pattern tests
  • pat-if-let-chains - Use if let chains to combine pattern bindings and conditions
  • pat-exhaustive-enum - Match owned enums exhaustively; avoid catch-all _ that hides new variants
  • pat-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 it
  • macro-rules-hygiene - Rely on macro_rules! hygiene and use $crate for paths to your crate's items
  • macro-fragment-specifiers - Capture with precise fragment specifiers, not raw :tt, where you can
  • macro-export-crate-path - Export declarative macros with #[macro_export] and a clean import path
  • macro-private-helpers - Hide macro-generated helper items behind a #[doc(hidden)] pub mod __private
  • macro-proc-two-crate - Put procedural macros in a dedicated proc-macro = true crate and re-export from the facade
  • macro-proc-syn-quote - Build procedural macros with syn, quote, and proc-macro2
  • macro-proc-error-spans - Report proc-macro errors as spanned compile errors, never by panicking
  • macro-cfg-select - Use cfg_select! (stable since Rust 1.95) to pick one compile-time branch instead of stacked #[cfg] or the cfg-if crate
  • macro-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 restrictive Fn trait a callback needs (FnOnce ⊇ FnMut ⊇ Fn)
  • closure-impl-fn-return - Return closures as impl Fn/FnMut/FnOnce, not Box<dyn Fn>
  • closure-move-capture - Use move for closures that outlive the current scope; clone before move to keep the original
  • closure-static-vs-dyn - Accept impl Fn (generic) for hot callbacks; use &dyn Fn/Box<dyn Fn> to cut code size or to store them
  • closure-disjoint-capture - Capture only what you use; lean on edition-2021 disjoint closure captures

18. Collections (MEDIUM)

  • coll-binaryheap - Use BinaryHeap for a priority queue or repeated max-extraction
  • coll-map-choice - Pick the map by access pattern: HashMap (fast, unordered), BTreeMap (sorted / range queries), IndexMap (insertion order)
  • coll-seq-choice - Default to Vec; use VecDeque for queue/deque behaviour; avoid LinkedList
  • coll-set-membership - Use HashSet/BTreeSet for membership tests and dedup, not linear Vec::contains

19. Naming Conventions (MEDIUM)

  • name-types-camel - Use UpperCamelCase for types, traits, and enum names
  • name-variants-camel - Use UpperCamelCase for enum variants
  • name-funcs-snake - Use snake_case for functions, methods, variables, and modules
  • name-consts-screaming - Use SCREAMING_SNAKE_CASE for constants and statics
  • name-lifetime-short - Use short, conventional lifetime names: 'a, 'b, 'de, 'src
  • name-type-param-single - Use single uppercase letters for type parameters: T, E, K, V
  • name-as-free - Use the as_ prefix for free, borrowed-to-borrowed conversions
  • name-to-expensive - Use to_ prefix for expensive conversions that allocate or compute
  • name-into-ownership - Use into_ prefix for ownership-consuming conversions
  • name-no-get-prefix - Omit get_ prefix for simple getters
  • name-is-has-bool - Use is_, has_, can_, should_ prefixes for boolean-returning methods
  • name-iter-method - Name iterator methods iter(), iter_mut(), and into_iter(), and implement IntoIterator for owned, &, and &mut
  • name-iter-type-match - Name iterator types after their source method
  • name-acronym-word - Treat acronyms as words in identifiers: HttpServer, not HTTPServer
  • name-crate-no-rs - Name crates for what they do, without a -rs or -rust suffix
  • name-weasel-words - Name types for what they do; replace Service, 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 module
  • test-use-super - Use use super::*; in test modules to access parent module items
  • test-integration-dir - Put integration tests in the tests/ directory
  • test-descriptive-names - Use descriptive test names that explain what is being tested
  • test-arrange-act-assert - Structure tests with clear Arrange, Act, Assert sections
  • test-proptest-properties - Use proptest for property-based testing
  • test-mockall-mocking - Use mockall for trait mocking
  • test-mock-traits - Use traits for dependencies to enable mocking in tests
  • test-fixture-raii - Use RAII pattern (Drop trait) for automatic test cleanup
  • test-tokio-async - Use #[tokio::test] for async tests
  • test-should-panic - Use #[should_panic] to test that code panics as expected
  • test-criterion-bench - Use criterion for benchmarking
  • test-doctest-examples - Keep documentation examples as executable doctests
  • test-loom-concurrency - Use loom to exhaustively test lock-free and concurrent code
  • test-snapshot-testing - Use snapshot testing (insta) for complex or serialized output
  • test-no-tautological - Test properties and independently known values, not a restatement of the code under test
  • test-utils-feature-gated - Put mocks, fake data, and safety-check overrides behind a test-util feature

21. Documentation (MEDIUM)

  • doc-all-public - Document all public items with /// doc comments
  • doc-module-inner - Use //! for module-level documentation
  • doc-examples-section - Include # Examples with runnable code
  • doc-errors-section - Give every fallible public function an # Errors section that lists each failure condition and links the error variants
  • doc-panics-section - Include # Panics section for functions that can panic
  • doc-safety-section - Include # Safety section for unsafe functions
  • doc-question-mark - Use ? in examples, not .unwrap()
  • doc-hidden-setup - Use # prefix to hide example setup code
  • doc-intra-links - Link types, methods, and modules in doc comments with intra-doc links such as [Type] and [Self::method]
  • doc-cargo-metadata - Fill Cargo.toml metadata for published crates
  • doc-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 expect
  • doc-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 - Use tracing for structured, span-aware diagnostics instead of println! or bare log
  • obs-library-facade - Libraries emit through the tracing/log facade and never install a subscriber
  • obs-structured-fields - Record structured key-value fields, not values interpolated into the message string
  • obs-instrument-spans - Use #[tracing::instrument] and spans to attach context to async tasks and requests
  • obs-levels-filter - Use log levels meaningfully and filter with EnvFilter / RUST_LOG
  • obs-error-chain - Log errors with their full source chain, and log each error exactly once
  • obs-no-sensitive-data - Redact or skip secrets and PII before they reach a log; never log them raw
  • obs-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 with iter(), iter_mut(), zip and adapters instead of indexing in a 0..len loop
  • perf-iter-lazy - Keep iterators lazy, collect only when needed
  • perf-collect-once - Chain iterator adapters and collect once at the end, or not at all
  • perf-entry-api - Use entry API for map insert-or-update
  • perf-drain-reuse - Use drain to reuse allocations
  • perf-extend-batch - Use extend for batch insertions
  • perf-chain-avoid - Use a single iterator or an explicit loop in hot loops; chain adds a branch per item
  • perf-collect-into - Use collect_into for reusing containers
  • perf-black-box-bench - Use black_box in benchmarks
  • perf-release-profile - Optimize release profile settings
  • perf-profile-first - Profile under a realistic workload, then optimize only the measured hot spot
  • perf-ahash - Use a faster hasher (ahash / FxHashMap) when DoS resistance is not needed
  • perf-io-buffering - Wrap Read/Write in BufReader/BufWriter for many small operations

24. Project Structure (LOW)

  • proj-lib-main-split - Keep main.rs minimal, logic in lib.rs
  • proj-mod-by-feature - Organize modules by feature, not type
  • proj-flat-small - Keep small projects flat
  • proj-mod-rs-dir - Use mod.rs for multi-file modules
  • proj-pub-crate-internal - Use pub(crate) for internal APIs
  • proj-pub-super-parent - Use pub(super) for parent-only visibility
  • proj-pub-use-reexport - Use pub use for clean public API
  • proj-prelude-module - Create prelude module for common imports
  • proj-bin-dir - Put multiple binaries in src/bin/
  • proj-workspace-large - Use workspaces for large projects
  • proj-workspace-deps - Use workspace dependency inheritance for consistent versions across crates
  • proj-feature-additive - Design Cargo features to be strictly additive
  • proj-msrv-declare - Declare rust-version (MSRV) in Cargo.toml and test it in CI
  • proj-build-rs-minimal - Keep build.rs minimal, deterministic, and idempotent
  • proj-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 selectively
  • lint-missing-docs - Warn on missing documentation for public items
  • lint-unsafe-doc - Require documentation for unsafe blocks
  • lint-cargo-metadata - Enable clippy::cargo for published crates
  • lint-rustfmt-check - Run cargo fmt --check in CI
  • lint-workspace-lints - Configure lints at workspace level for consistent enforcement
  • lint-cfg-check - Enable unexpected_cfgs and declare known cfgs to catch feature-gate typos
  • lint-clippy-nursery-selected - Enable high-value clippy::nursery lints selectively, not the whole group
  • lint-build-warnings - Deny warnings in CI with build.warnings instead of RUSTFLAGS=-Dwarnings
  • lint-cargo-lints - Configure Cargo's own lints in [lints.cargo] and deny unused dependencies
  • lint-expect-over-allow - Use #[expect(lint, reason = "...")] instead of #[allow] when overriding a lint for one item
  • lint-clippy-groups - Keep clippy's default groups on — correctness at deny; suspicious, style, complexity, and perf at 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 commented
  • anti-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
This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

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.

Install on Skills Hub badge preview
Markdown
[![Install on Skills Hub](https://skills-hub.ai/api/badges/skill/rust-skills)](https://skills-hub.ai/skills/rust-skills)
HTML
<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.