Skip to content
Back to search

rust-skills

SkillWorks with Claude CodeGitHub

Comprehensive Rust coding guidelines with 265 rules across 26 categories. Use when writing, reviewing, or refactoring Rust code. Covers ownership, error handling, async patterns, concurrency, unsafe code, API design, memory optimization, performance, numeric safety, conversions, serde, pattern matching, macros, closures, observability, testing, and common anti-patterns. Invoke with /rust-skills.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/leonardomso-rust-skills/badge.svg)](/listings/leonardomso-rust-skills)

HTML

<a href="/listings/leonardomso-rust-skills"><img src="/api/listings/leonardomso-rust-skills/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

npx add-skill leonardomso/rust-skills

That's it. The CLI figures out which agents you have and installs the skill to the right place.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 499 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. ---
  2. name: rust-skills
  3. description: >
  4. Comprehensive Rust coding guidelines with 265 rules across 26 categories.
  5. Use when writing, reviewing, or refactoring Rust code. Covers ownership,
  6. error handling, async patterns, concurrency, unsafe code, API design, memory
  7. optimization, performance, numeric safety, conversions, serde, pattern
  8. matching, macros, closures, observability, testing, and common anti-patterns.
  9. Invoke with /rust-skills.
  10. license: MIT
  11. metadata:
  12. author: leonardomso
  13. version: "1.5.1"
  14. sources:
  15. - Rust API Guidelines
  16. - Rust Performance Book
  17. - Rust 2024 Edition Guide
  18. - The Rustonomicon
  19. - ripgrep, tokio, serde, polars, axum, cargo codebases
  20. ---
  21. # Rust Best Practices
  22. Comprehensive guide for writing high-quality, idiomatic, and highly optimized Rust code. Contains 265 rules across 26 categories, prioritized by impact to guide LLMs in code generation and refactoring. Current for Rust 1.96 (2024 edition).
  23. ## When to Apply
  24. Reference these guidelines when:
  25. - Writing new Rust functions, structs, or modules
  26. - Implementing error handling or async code
  27. - Writing concurrent, parallel, or `unsafe` code
  28. - Designing public APIs for libraries
  29. - Reviewing code for ownership/borrowing issues
  30. - Optimizing memory usage or reducing allocations
  31. - Tuning performance for hot paths
  32. - Refactoring existing Rust code
  33. ## Rule Categories by Priority
  34. | Priority | Category | Impact | Prefix | Rules |
  35. |----------|----------|--------|--------|-------|
  36. | 1 | Ownership & Borrowing | CRITICAL | `own-` | 12 |
  37. | 2 | Error Handling | CRITICAL | `err-` | 12 |
  38. | 3 | Memory Optimization | CRITICAL | `mem-` | 17 |
  39. | 4 | Unsafe Code | CRITICAL | `unsafe-` | 7 |
  40. | 5 | API Design | HIGH | `api-` | 17 |
  41. | 6 | Async/Await | HIGH | `async-` | 18 |
  42. | 7 | Concurrency | HIGH | `conc-` | 4 |
  43. | 8 | Compiler Optimization | HIGH | `opt-` | 12 |
  44. | 9 | Numeric & Arithmetic Safety | HIGH | `num-` | 5 |
  45. | 10 | Type Safety | MEDIUM | `type-` | 13 |
  46. | 11 | Trait & Generics Design | MEDIUM | `trait-` | 6 |
  47. | 12 | Conversions | MEDIUM | `conv-` | 3 |
  48. | 13 | Const & Compile-Time | MEDIUM | `const-` | 4 |
  49. | 14 | Serde | MEDIUM | `serde-` | 8 |
  50. | 15 | Pattern Matching | MEDIUM | `pat-` | 5 |
  51. | 16 | Macros | MEDIUM | `macro-` | 8 |
  52. | 17 | Closures | MEDIUM | `closure-` | 5 |
  53. | 18 | Collections | MEDIUM | `coll-` | 4 |
  54. | 19 | Naming Conventions | MEDIUM | `name-` | 16 |
  55. | 20 | Testing | MEDIUM | `test-` | 15 |
  56. | 21 | Documentation | MEDIUM | `doc-` | 12 |
  57. | 22 | Observability | MEDIUM | `obs-` | 7 |
  58. | 23 | Performance Patterns | MEDIUM | `perf-` | 13 |
  59. | 24 | Project Structure | LOW | `proj-` | 14 |
  60. | 25 | Clippy & Linting | LOW | `lint-` | 13 |
  61. | 26 | Anti-patterns | REFERENCE | `anti-` | 15 |
  62. ---
  63. ## Quick Reference
  64. ### 1. Ownership & Borrowing (CRITICAL)
  65. - [`own-borrow-over-clone`](rules/own-borrow-over-clone.md) - Prefer `&T` borrowing over `.clone()`
  66. - [`own-slice-over-vec`](rules/own-slice-over-vec.md) - Accept `&[T]` not `&Vec<T>`, `&str` not `&String`
  67. - [`own-cow-conditional`](rules/own-cow-conditional.md) - Use `Cow<'a, T>` for conditional ownership
  68. - [`own-arc-shared`](rules/own-arc-shared.md) - Use `Arc<T>` for thread-safe shared ownership
  69. - [`own-rc-single-thread`](rules/own-rc-single-thread.md) - Use `Rc<T>` for shared ownership in single-threaded contexts
  70. - [`own-refcell-interior`](rules/own-refcell-interior.md) - Use `RefCell<T>` for interior mutability in single-threaded code
  71. - [`own-mutex-interior`](rules/own-mutex-interior.md) - Use `Mutex<T>` for interior mutability across threads
  72. - [`own-rwlock-readers`](rules/own-rwlock-readers.md) - Use `RwLock<T>` when reads significantly outnumber writes
  73. - [`own-copy-small`](rules/own-copy-small.md) - Implement `Copy` for small, simple types
  74. - [`own-clone-explicit`](rules/own-clone-explicit.md) - Use explicit `Clone` for types where copying has meaningful cost
  75. - [`own-move-large`](rules/own-move-large.md) - Move large types instead of copying; use `Box` if moves are expensive
  76. - [`own-lifetime-elision`](rules/own-lifetime-elision.md) - Rely on lifetime elision rules; add explicit lifetimes only when required
  77. ### 2. Error Handling (CRITICAL)
  78. - [`err-thiserror-lib`](rules/err-thiserror-lib.md) - Use `thiserror` for library error types
  79. - [`err-anyhow-app`](rules/err-anyhow-app.md) - Use `anyhow` for application error handling
  80. - [`err-result-over-panic`](rules/err-result-over-panic.md) - Return `Result<T, E>` instead of panicking for recoverable errors
  81. - [`err-context-chain`](rules/err-context-chain.md) - Add context with `.context()` or `.with_context()`
  82. - [`err-no-unwrap-prod`](rules/err-no-unwrap-prod.md) - Avoid `unwrap()` in production code; use `?`, `expect()`, or handle errors
  83. - [`err-expect-bugs-only`](rules/err-expect-bugs-only.md) - Use `expect()` only for invariants that indicate bugs, not user errors
  84. - [`err-question-mark`](rules/err-question-mark.md) - Use `?` operator for clean propagation
  85. - [`err-from-impl`](rules/err-from-impl.md) - Implement `From<E>` for error conversions to enable `?` operator
  86. - [`err-source-chain`](rules/err-source-chain.md) - Preserve error chains with `#[source]` or `source()` method
  87. - [`err-lowercase-msg`](rules/err-lowercase-msg.md) - Start error messages lowercase, no trailing punctuation
  88. - [`err-doc-errors`](rules/err-doc-errors.md) - Document error conditions with `# Errors` section in doc comments
  89. - [`err-custom-type`](rules/err-custom-type.md) - Define custom error types for domain-specific failures
  90. ### 3. Memory Optimization (CRITICAL)
  91. - [`mem-with-capacity`](rules/mem-with-capacity.md) - Use `with_capacity()` when size is known
  92. - [`mem-smallvec`](rules/mem-smallvec.md) - Use `SmallVec` for usually-small collections
  93. - [`mem-arrayvec`](rules/mem-arrayvec.md) - Use `ArrayVec<T, N>` for fixed-capacity collections that never heap-allocate
  94. - [`mem-box-large-variant`](rules/mem-box-large-variant.md) - Box large enum variants to reduce overall enum size
  95. - [`mem-boxed-slice`](rules/mem-boxed-slice.md) - Use `Box<[T]>` instead of `Vec<T>` for fixed-size heap data
  96. - [`mem-thinvec`](rules/mem-thinvec.md) - Use `ThinVec<T>` for nullable collections with minimal overhead
  97. - [`mem-clone-from`](rules/mem-clone-from.md) - Use `clone_from()` to reuse allocations when repeatedly cloning
  98. - [`mem-reuse-collections`](rules/mem-reuse-collections.md) - Clear and reuse collections instead of creating new ones in loops
  99. - [`mem-avoid-format`](rules/mem-avoid-format.md) - Avoid `format!()` when string literals work
  100. - [`mem-write-over-format`](rules/mem-write-over-format.md) - Use `write!()` into existing buffers instead of `format!()` allocations
  101. - [`mem-arena-allocator`](rules/mem-arena-allocator.md) - Use arena allocators for batch allocations
  102. - [`mem-zero-copy`](rules/mem-zero-copy.md) - Use zero-copy patterns with slices and `Bytes`
  103. - [`mem-compact-string`](rules/mem-compact-string.md) - Use compact string types for memory-constrained string storage
  104. - [`mem-smaller-integers`](rules/mem-smaller-integers.md) - Use appropriately-sized integers to reduce memory footprint
  105. - [`mem-assert-type-size`](rules/mem-assert-type-size.md) - Use static assertions to guard against accidental type size growth
  106. - [`mem-take-replace`](rules/mem-take-replace.md) - Use `mem::take` / `mem::replace` to move a value out of a `&mut` without cloning
  107. - [`mem-drop-order`](rules/mem-drop-order.md) - Know and control drop order: struct fields drop top-to-bottom, locals in reverse
  108. ### 4. Unsafe Code (CRITICAL)
  109. - [`unsafe-safety-comment`](rules/unsafe-safety-comment.md) - Write a `// SAFETY:` comment above every `unsafe` block and a `# Safety` section in every `unsafe fn`.
  110. - [`unsafe-minimize-scope`](rules/unsafe-minimize-scope.md) - Keep `unsafe` blocks as small as possible — mark only the operation that requires unsafety, not the surrounding safe code.
  111. - [`unsafe-miri-ci`](rules/unsafe-miri-ci.md) - Run `cargo miri test` in CI for every crate that contains `unsafe` code.
  112. - [`unsafe-maybeuninit`](rules/unsafe-maybeuninit.md) - Use `MaybeUninit<T>` for uninitialized memory; never use `mem::uninitialized()` or `mem::zeroed()` for types with validity invariants.
  113. - [`unsafe-extern-block`](rules/unsafe-extern-block.md) - In Rust 2024, wrap `extern` blocks in `unsafe extern { }` and annotate each item as `safe` or `unsafe`.
  114. - [`unsafe-send-sync-manual`](rules/unsafe-send-sync-manual.md) - Document the invariants when manually implementing `Send` or `Sync`; prefer letting the compiler derive them automatically.
  115. - [`unsafe-no-mangle-unsafe`](rules/unsafe-no-mangle-unsafe.md) - In Rust 2024, write `#[unsafe(no_mangle)]`, `#[unsafe(export_name = "...")]`, and `#[unsafe(link_section = "...")]` — not the bare attribute forms.
  116. ### 5. API Design (HIGH)
  117. - [`api-builder-pattern`](rules/api-builder-pattern.md) - Use Builder pattern for complex construction
  118. - [`api-builder-must-use`](rules/api-builder-must-use.md) - Mark builder methods with `#[must_use]` to prevent silent drops
  119. - [`api-newtype-safety`](rules/api-newtype-safety.md) - Use newtypes to prevent mixing semantically different values
  120. - [`api-typestate`](rules/api-typestate.md) - Use typestate pattern to encode state machine invariants in the type system
  121. - [`api-sealed-trait`](rules/api-sealed-trait.md) - Use sealed traits to prevent external implementations while allowing use
  122. - [`api-extension-trait`](rules/api-extension-trait.md) - Use extension traits to add methods to external types
  123. - [`api-parse-dont-validate`](rules/api-parse-dont-validate.md) - Parse into validated types at boundaries
  124. - [`api-impl-into`](rules/api-impl-into.md) - Accept `impl Into<T>` for flexible APIs, implement `From<T>` for conversions
  125. - [`api-impl-asref`](rules/api-impl-asref.md) - Use `AsRef<T>` when you only need to borrow the inner data
  126. - [`api-must-use`](rules/api-must-use.md) - Mark types and functions with `#[must_use]` when ignoring results is likely a bug
  127. - [`api-non-exhaustive`](rules/api-non-exhaustive.md) - Use `#[non_exhaustive]` on public enums and structs for forward compatibility
  128. - [`api-from-not-into`](rules/api-from-not-into.md) - Implement `From<T>`, not `Into<U>` - From gives you Into for free
  129. - [`api-default-impl`](rules/api-default-impl.md) - Implement `Default` for types with sensible default values
  130. - [`api-common-traits`](rules/api-common-traits.md) - Implement standard traits (Debug, Clone, PartialEq, etc.) for public types
  131. - [`api-serde-optional`](rules/api-serde-optional.md) - Make serde a feature flag, not a hard dependency for library crates
  132. - [`api-impl-fromiterator`](rules/api-impl-fromiterator.md) - Implement `FromIterator` and `Extend` for collection types, and `IntoIterator` for all three reference forms
  133. - [`api-operator-overload`](rules/api-operator-overload.md) - Overload operators only when the semantics are natural and unsurprising
  134. ### 6. Async/Await (HIGH)
  135. - [`async-tokio-runtime`](rules/async-tokio-runtime.md) - Configure Tokio runtime appropriately for your workload
  136. - [`async-no-lock-await`](rules/async-no-lock-await.md) - Never hold `Mutex`/`RwLock` across `.await`
  137. - [`async-spawn-blocking`](rules/async-spawn-blocking.md) - Use `spawn_blocking` for CPU-intensive work
  138. - [`async-tokio-fs`](rules/async-tokio-fs.md) - Use `tokio::fs` instead of `std::fs` in async code
  139. - [`async-cancellation-token`](rules/async-cancellation-token.md) - Use `CancellationToken` for graceful shutdown and task cancellation
  140. - [`async-join-parallel`](rules/async-join-parallel.md) - Use `join!` or `try_join!` for concurrent independent futures
  141. - [`async-try-join`](rules/async-try-join.md) - Use `try_join!` for concurrent fallible operations with early return on error
  142. - [`async-select-racing`](rules/async-select-racing.md) - Use `select!` to race futures and handle the first to complete
  143. - [`async-bounded-channel`](rules/async-bounded-channel.md) - Use bounded channels to apply backpressure and prevent unbounded memory growth
  144. - [`async-mpsc-queue`](rules/async-mpsc-queue.md) - Use `mpsc` channels for async message queues between tasks
  145. - [`async-broadcast-pubsub`](rules/async-broadcast-pubsub.md) - Use `broadcast` channel for pub/sub where all subscribers receive all messages
  146. - [`async-watch-latest`](rules/async-watch-latest.md) - Use `watch` channel for sharing the latest value with multiple observers
  147. - [`async-oneshot-response`](rules/async-oneshot-response.md) - Use `oneshot` channel for request-response patterns
  148. - [`async-joinset-structured`](rules/async-joinset-structured.md) - Use `JoinSet` for managing dynamic collections of spawned tasks
  149. - [`async-clone-before-await`](rules/async-clone-before-await.md) - Clone Arc/Rc data before await points to avoid holding references across suspension
  150. - [`async-fn-in-trait`](rules/async-fn-in-trait.md) - Use native `async fn` in traits (stable 1.75) instead of the `async_trait` macro
  151. - [`async-async-fn-bounds`](rules/async-async-fn-bounds.md) - Use `AsyncFn`/`AsyncFnMut`/`AsyncFnOnce` bounds instead of `F: Fn() -> Fut, Fut: Future`
  152. - [`async-cancel-safety`](rules/async-cancel-safety.md) - Ensure futures used in `tokio::select!` branches are cancellation-safe
  153. ### 7. Concurrency (HIGH)
  154. - [`conc-rayon-par-iter`](rules/conc-rayon-par-iter.md) - Use rayon's `par_iter()` for CPU-bound data parallelism
  155. - [`conc-scoped-threads`](rules/conc-scoped-threads.md) - Use `std::thread::scope` to borrow stack data across threads
  156. - [`conc-atomic-ordering`](rules/conc-atomic-ordering.md) - Use the weakest correct memory `Ordering` for every atomic operation
  157. - [`conc-thread-local`](rules/conc-thread-local.md) - Prefer `thread_local!` with `Cell`/`RefCell` over `static mut`
  158. ### 8. Compiler Optimization (HIGH)
  159. - [`opt-inline-small`](rules/opt-inline-small.md) - Use `#[inline]` for small hot functions
  160. - [`opt-inline-always-rare`](rules/opt-inline-always-rare.md) - Use `#[inline(always)]` sparingly—only for critical hot paths proven by profiling
  161. - [`opt-inline-never-cold`](rules/opt-inline-never-cold.md) - Use `#[inline(never)]` and `#[cold]` for error paths and rarely-executed code
  162. - [`opt-cold-unlikely`](rules/opt-cold-unlikely.md) - Mark unlikely code paths with `#[cold]` to help compiler optimization
  163. - [`opt-likely-hint`](rules/opt-likely-hint.md) - Use code structure to hint at likely branches; use intrinsics on nightly
  164. - [`opt-lto-release`](rules/opt-lto-release.md) - Enable LTO in release builds
  165. - [`opt-codegen-units`](rules/opt-codegen-units.md) - Set `codegen-units = 1` for maximum optimization in release builds
  166. - [`opt-pgo-profile`](rules/opt-pgo-profile.md) - Use Profile-Guided Optimization (PGO) for maximum performance
  167. - [`opt-target-cpu`](rules/opt-target-cpu.md) - Use `target-cpu=native` for maximum performance on known deployment targets
  168. - [`opt-bounds-check`](rules/opt-bounds-check.md) - Use iterators and patterns that eliminate bounds checks in hot paths
  169. - [`opt-simd-portable`](rules/opt-simd-portable.md) - Use portable SIMD for vectorized operations across architectures
  170. - [`opt-cache-friendly`](rules/opt-cache-friendly.md) - Organize data for cache-efficient access patterns
  171. ### 9. Numeric & Arithmetic Safety (HIGH)
  172. - [`num-overflow-explicit`](rules/num-overflow-explicit.md) - Handle integer overflow explicitly: `checked_`/`saturating_`/`wrapping_`/`overflowing_`
  173. - [`num-cast-try-from`](rules/num-cast-try-from.md) - Avoid `as` for narrowing casts; use `From` for widening and `TryFrom` for narrowing
  174. - [`num-float-compare`](rules/num-float-compare.md) - Don't compare floats with `==`; use a tolerance, and `total_cmp` for ordering
  175. - [`num-saturating-clamp`](rules/num-saturating-clamp.md) - Bound values with `clamp` and saturating arithmetic
  176. - [`num-nonzero`](rules/num-nonzero.md) - Use `NonZero*` types to forbid zero and unlock the niche optimization
  177. ### 10. Type Safety (MEDIUM)
  178. - [`type-newtype-ids`](rules/type-newtype-ids.md) - Wrap IDs in newtypes: `UserId(u64)`
  179. - [`type-newtype-validated`](rules/type-newtype-validated.md) - Use newtypes to enforce validation at construction time
  180. - [`type-enum-states`](rules/type-enum-states.md) - Use enums for mutually exclusive states
  181. - [`type-option-nullable`](rules/type-option-nullable.md) - Use `Option<T>` for values that might not exist
  182. - [`type-result-fallible`](rules/type-result-fallible.md) - Use `Result<T, E>` for operations that can fail
  183. - [`type-phantom-marker`](rules/type-phantom-marker.md) - Use `PhantomData` to express type relationships without runtime cost
  184. - [`type-never-diverge`](rules/type-never-diverge.md) - Use `!` (never type) for functions that never return
  185. - [`type-generic-bounds`](rules/type-generic-bounds.md) - Add trait bounds only where needed, prefer where clauses for readability
  186. - [`type-no-stringly`](rules/type-no-stringly.md) - Avoid stringly-typed APIs; use enums, newtypes, or validated types
  187. - [`type-repr-transparent`](rules/type-repr-transparent.md) - Use `#[repr(transparent)]` for newtypes in FFI contexts
  188. - [`type-deref-coercion`](rules/type-deref-coercion.md) - Implement `Deref`/`DerefMut` only for smart-pointer and transparent wrapper types
  189. - [`type-display-vs-debug`](rules/type-display-vs-debug.md) - Use `Display` for user-facing output and `Debug` for diagnostics; never swap them
  190. - [`type-numeric-fmt`](rules/type-numeric-fmt.md) - Implement `LowerHex`, `UpperHex`, `Octal`, and `Binary` for numeric newtypes
  191. ### 11. Trait & Generics Design (MEDIUM)
  192. - [`trait-associated-type-vs-generic`](rules/trait-associated-type-vs-generic.md) - 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
  193. - [`trait-blanket-impl`](rules/trait-blanket-impl.md) - Use a blanket impl `impl<T: Bound> Trait for T` to give behaviour to every type that satisfies a bound
  194. - [`trait-coherence-newtype`](rules/trait-coherence-newtype.md) - Respect the orphan rule; wrap a foreign type in a newtype to implement a foreign trait on it
  195. - [`trait-default-methods`](rules/trait-default-methods.md) - Define a trait in terms of a few required methods plus defaulted ones built on top of them
  196. - [`trait-dyn-vs-generic`](rules/trait-dyn-vs-generic.md) - Choose static dispatch (generics / `impl Trait`) vs dynamic dispatch (`dyn Trait`) deliberately
  197. - [`trait-object-safety`](rules/trait-object-safety.md) - Keep a trait dyn-compatible (object-safe) when you need `dyn Trait`
  198. ### 12. Conversions (MEDIUM)
  199. - [`conv-tryfrom-fallible`](rules/conv-tryfrom-fallible.md) - Implement `TryFrom` for fallible conversions instead of ad-hoc conversion functions
  200. - [`conv-fromstr-parsing`](rules/conv-fromstr-parsing.md) - Implement `FromStr` to enable `str::parse` for string-to-type conversions
  201. - [`conv-asmut-mutable`](rules/conv-asmut-mutable.md) - Accept `impl AsMut<T>` for flexible mutable borrowed inputs instead of concrete mutable references
  202. ### 13. Const & Compile-Time (MEDIUM)
  203. - [`const-block`](rules/const-block.md) - Use inline `const { }` blocks for compile-time evaluation and assertions
  204. - [`const-fn`](rules/const-fn.md) - Make functions `const fn` when they can run at compile time
  205. - [`const-generics`](rules/const-generics.md) - Parameterize over values with const generics `<const N: usize>`
  206. - [`const-vs-static`](rules/const-vs-static.md) - Use `const` for an inlined value and `static` for a single addressed instance
  207. ### 14. Serde (MEDIUM)
  208. - [`serde-rename-all`](rules/serde-rename-all.md) - Match the external naming convention with `#[serde(rename_all = ...)]`
  209. - [`serde-default-compat`](rules/serde-default-compat.md) - Use `#[serde(default)]` for optional and backward-compatible fields
  210. - [`serde-skip-empty`](rules/serde-skip-empty.md) - Omit empty fields with `skip_serializing_if`
  211. - [`serde-flatten`](rules/serde-flatten.md) - Inline nested structs or capture extra keys with `#[serde(flatten)]`
  212. - [`serde-enum-representation`](rules/serde-enum-representation.md) - Choose enum tagging deliberately: externally, internally, adjacently tagged, or untagged
  213. - [`serde-deny-unknown-fields`](rules/serde-deny-unknown-fields.md) - Reject unexpected keys with `#[serde(deny_unknown_fields)]`
  214. - [`serde-custom-with`](rules/serde-custom-with.md) - Customize a field's (de)serialization with `with` / `serialize_with` / `deserialize_with`
  215. - [`serde-try-from-validate`](rules/serde-try-from-validate.md) - Validate while deserializing with `#[serde(try_from = "Raw")]`
  216. ### 15. Pattern Matching (MEDIUM)
  217. - [`pat-let-else`](rules/pat-let-else.md) - Use `let ... else` for early-return pattern extraction
  218. - [`pat-matches-macro`](rules/pat-matches-macro.md) - Use `matches!()` for boolean pattern tests
  219. - [`pat-if-let-chains`](rules/pat-if-let-chains.md) - Use `if let` chains to combine pattern bindings and conditions
  220. - [`pat-exhaustive-enum`](rules/pat-exhaustive-enum.md) - Match owned enums exhaustively; avoid catch-all `_` that hides new variants
  221. - [`pat-at-bindings`](rules/pat-at-bindings.md) - Use `@` bindings to capture a value while matching it against a pattern
  222. ### 16. Macros (MEDIUM)
  223. - [`macro-prefer-functions`](rules/macro-prefer-functions.md) - Reach for a macro only when a function or generic cannot express it
  224. - [`macro-rules-hygiene`](rules/macro-rules-hygiene.md) - Rely on `macro_rules!` hygiene and use `$crate` for paths to your crate's items
  225. - [`macro-fragment-specifiers`](rules/macro-fragment-specifiers.md) - Capture with precise fragment specifiers, not raw `:tt`, where you can
  226. - [`macro-export-crate-path`](rules/macro-export-crate-path.md) - Export declarative macros with `#[macro_export]` and a clean import path
  227. - [`macro-private-helpers`](rules/macro-private-helpers.md) - Hide macro-generated helper items behind a `#[doc(hidden)] pub mod __private`
  228. - [`macro-proc-two-crate`](rules/macro-proc-two-crate.md) - Put procedural macros in a dedicated `proc-macro = true` crate and re-export from the facade
  229. - [`macro-proc-syn-quote`](rules/macro-proc-syn-quote.md) - Build procedural macros with `syn`, `quote`, and `proc-macro2`
  230. - [`macro-proc-error-spans`](rules/macro-proc-error-spans.md) - Report proc-macro errors as spanned compile errors, never by panicking
  231. ### 17. Closures (MEDIUM)
  232. - [`closure-fn-trait-bounds`](rules/closure-fn-trait-bounds.md) - Require the least restrictive `Fn` trait a callback needs (`FnOnce` ⊇ `FnMut` ⊇ `Fn`)
  233. - [`closure-impl-fn-return`](rules/closure-impl-fn-return.md) - Return closures as `impl Fn`/`FnMut`/`FnOnce`, not `Box<dyn Fn>`
  234. - [`closure-move-capture`](rules/closure-move-capture.md) - Use `move` for closures that outlive the current scope; clone before `move` to keep the original
  235. - [`closure-static-vs-dyn`](rules/closure-static-vs-dyn.md) - Accept `impl Fn` (generic) for hot callbacks; use `&dyn Fn`/`Box<dyn Fn>` to cut code size or to store them
  236. - [`closure-disjoint-capture`](rules/closure-disjoint-capture.md) - Capture only what you use; lean on edition-2021 disjoint closure captures
  237. ### 18. Collections (MEDIUM)
  238. - [`coll-binaryheap`](rules/coll-binaryheap.md) - Use `BinaryHeap` for a priority queue or repeated max-extraction
  239. - [`coll-map-choice`](rules/coll-map-choice.md) - Pick the map by access pattern: `HashMap` (fast, unordered), `BTreeMap` (sorted / range queries), `IndexMap` (insertion order)
  240. - [`coll-seq-choice`](rules/coll-seq-choice.md) - Default to `Vec`; use `VecDeque` for queue/deque behaviour; avoid `LinkedList`
  241. - [`coll-set-membership`](rules/coll-set-membership.md) - Use `HashSet`/`BTreeSet` for membership tests and dedup, not linear `Vec::contains`
  242. ### 19. Naming Conventions (MEDIUM)
  243. - [`name-types-camel`](rules/name-types-camel.md) - Use `UpperCamelCase` for types, traits, and enum names
  244. - [`name-variants-camel`](rules/name-variants-camel.md) - Use `UpperCamelCase` for enum variants
  245. - [`name-funcs-snake`](rules/name-funcs-snake.md) - Use `snake_case` for functions, methods, variables, and modules
  246. - [`name-consts-screaming`](rules/name-consts-screaming.md) - Use `SCREAMING_SNAKE_CASE` for constants and statics
  247. - [`name-lifetime-short`](rules/name-lifetime-short.md) - Use short, conventional lifetime names: `'a`, `'b`, `'de`, `'src`
  248. - [`name-type-param-single`](rules/name-type-param-single.md) - Use single uppercase letters for type parameters: `T`, `E`, `K`, `V`
  249. - [`name-as-free`](rules/name-as-free.md) - `as_` prefix: free reference conversion
  250. - [`name-to-expensive`](rules/name-to-expensive.md) - Use `to_` prefix for expensive conversions that allocate or compute
  251. - [`name-into-ownership`](rules/name-into-ownership.md) - Use `into_` prefix for ownership-consuming conversions
  252. - [`name-no-get-prefix`](rules/name-no-get-prefix.md) - Omit get_ prefix for simple getters
  253. - [`name-is-has-bool`](rules/name-is-has-bool.md) - Use `is_`, `has_`, `can_`, `should_` prefixes for boolean-returning methods
  254. - [`name-iter-convention`](rules/name-iter-convention.md) - Use iter/iter_mut/into_iter for iterator methods
  255. - [`name-iter-method`](rules/name-iter-method.md) - Name iterator methods `iter()`, `iter_mut()`, and `into_iter()` consistently
  256. - [`name-iter-type-match`](rules/name-iter-type-match.md) - Name iterator types after their source method
  257. - [`name-acronym-word`](rules/name-acronym-word.md) - Treat acronyms as words in identifiers: `HttpServer`, not `HTTPServer`
  258. - [`name-crate-no-rs`](rules/name-crate-no-rs.md) - Don't suffix crate names with `-rs` or `-rust`
  259. ### 20. Testing (MEDIUM)
  260. - [`test-cfg-test-module`](rules/test-cfg-test-module.md) - Put unit tests in `#[cfg(test)] mod tests { }` within each module
  261. - [`test-use-super`](rules/test-use-super.md) - Use `use super::*;` in test modules to access parent module items
  262. - [`test-integration-dir`](rules/test-integration-dir.md) - Put integration tests in the `tests/` directory
  263. - [`test-descriptive-names`](rules/test-descriptive-names.md) - Use descriptive test names that explain what is being tested
  264. - [`test-arrange-act-assert`](rules/test-arrange-act-assert.md) - Structure tests with clear Arrange, Act, Assert sections
  265. - [`test-proptest-properties`](rules/test-proptest-properties.md) - Use proptest for property-based testing
  266. - [`test-mockall-mocking`](rules/test-mockall-mocking.md) - Use mockall for trait mocking
  267. - [`test-mock-traits`](rules/test-mock-traits.md) - Use traits for dependencies to enable mocking in tests
  268. - [`test-fixture-raii`](rules/test-fixture-raii.md) - Use RAII pattern (Drop trait) for automatic test cleanup
  269. - [`test-tokio-async`](rules/test-tokio-async.md) - Use `#[tokio::test]` for async tests
  270. - [`test-should-panic`](rules/test-should-panic.md) - Use `#[should_panic]` to test that code panics as expected
  271. - [`test-criterion-bench`](rules/test-criterion-bench.md) - Use `criterion` for benchmarking
  272. - [`test-doctest-examples`](rules/test-doctest-examples.md) - Keep documentation examples as executable doctests
  273. - [`test-loom-concurrency`](rules/test-loom-concurrency.md) - Use `loom` to exhaustively test lock-free and concurrent code
  274. - [`test-snapshot-testing`](rules/test-snapshot-testing.md) - Use snapshot testing (insta) for complex or serialized output
  275. ### 21. Documentation (MEDIUM)
  276. - [`doc-all-public`](rules/doc-all-public.md) - Document all public items with `///` doc comments
  277. - [`doc-module-inner`](rules/doc-module-inner.md) - Use `//!` for module-level documentation
  278. - [`doc-examples-section`](rules/doc-examples-section.md) - Include `# Examples` with runnable code
  279. - [`doc-errors-section`](rules/doc-errors-section.md) - Include `# Errors` section for fallible functions
  280. - [`doc-panics-section`](rules/doc-panics-section.md) - Include `# Panics` section for functions that can panic
  281. - [`doc-safety-section`](rules/doc-safety-section.md) - Include `# Safety` section for unsafe functions
  282. - [`doc-question-mark`](rules/doc-question-mark.md) - Use `?` in examples, not `.unwrap()`
  283. - [`doc-hidden-setup`](rules/doc-hidden-setup.md) - Use `# ` prefix to hide example setup code
  284. - [`doc-intra-links`](rules/doc-intra-links.md) - Use intra-doc links to reference types and items
  285. - [`doc-link-types`](rules/doc-link-types.md) - Use intra-doc links to connect related types and functions
  286. - [`doc-cargo-metadata`](rules/doc-cargo-metadata.md) - Fill `Cargo.toml` metadata for published crates
  287. - [`doc-crate-readme`](rules/doc-crate-readme.md) - Unify the README and crate root docs with `#![doc = include_str!("../README.md")]`
  288. ### 22. Observability (MEDIUM)
  289. - [`obs-tracing-over-log`](rules/obs-tracing-over-log.md) - Use `tracing` for structured, span-aware diagnostics instead of `println!` or bare `log`
  290. - [`obs-library-facade`](rules/obs-library-facade.md) - Libraries emit through the tracing/log facade and never install a subscriber
  291. - [`obs-structured-fields`](rules/obs-structured-fields.md) - Record structured key-value fields, not values interpolated into the message string
  292. - [`obs-instrument-spans`](rules/obs-instrument-spans.md) - Use `#[tracing::instrument]` and spans to attach context to async tasks and requests
  293. - [`obs-levels-filter`](rules/obs-levels-filter.md) - Use log levels meaningfully and filter with `EnvFilter` / `RUST_LOG`
  294. - [`obs-error-chain`](rules/obs-error-chain.md) - Log errors with their full source chain, and log each error exactly once
  295. - [`obs-no-sensitive-data`](rules/obs-no-sensitive-data.md) - Never log secrets or PII; redact or skip them
  296. ### 23. Performance Patterns (MEDIUM)
  297. - [`perf-iter-over-index`](rules/perf-iter-over-index.md) - Prefer iterators over manual indexing
  298. - [`perf-iter-lazy`](rules/perf-iter-lazy.md) - Keep iterators lazy, collect only when needed
  299. - [`perf-collect-once`](rules/perf-collect-once.md) - Don't collect intermediate iterators
  300. - [`perf-entry-api`](rules/perf-entry-api.md) - Use entry API for map insert-or-update
  301. - [`perf-drain-reuse`](rules/perf-drain-reuse.md) - Use drain to reuse allocations
  302. - [`perf-extend-batch`](rules/perf-extend-batch.md) - Use extend for batch insertions
  303. - [`perf-chain-avoid`](rules/perf-chain-avoid.md) - Avoid chain in hot loops
  304. - [`perf-collect-into`](rules/perf-collect-into.md) - Use collect_into for reusing containers
  305. - [`perf-black-box-bench`](rules/perf-black-box-bench.md) - Use black_box in benchmarks
  306. - [`perf-release-profile`](rules/perf-release-profile.md) - Optimize release profile settings
  307. - [`perf-profile-first`](rules/perf-profile-first.md) - Profile before optimizing
  308. - [`perf-ahash`](rules/perf-ahash.md) - Use a faster hasher (`ahash` / `FxHashMap`) when DoS resistance is not needed
  309. - [`perf-io-buffering`](rules/perf-io-buffering.md) - Wrap `Read`/`Write` in `BufReader`/`BufWriter` for many small operations
  310. ### 24. Project Structure (LOW)
  311. - [`proj-lib-main-split`](rules/proj-lib-main-split.md) - Keep `main.rs` minimal, logic in `lib.rs`
  312. - [`proj-mod-by-feature`](rules/proj-mod-by-feature.md) - Organize modules by feature, not type
  313. - [`proj-flat-small`](rules/proj-flat-small.md) - Keep small projects flat
  314. - [`proj-mod-rs-dir`](rules/proj-mod-rs-dir.md) - Use mod.rs for multi-file modules
  315. - [`proj-pub-crate-internal`](rules/proj-pub-crate-internal.md) - Use pub(crate) for internal APIs
  316. - [`proj-pub-super-parent`](rules/proj-pub-super-parent.md) - Use pub(super) for parent-only visibility
  317. - [`proj-pub-use-reexport`](rules/proj-pub-use-reexport.md) - Use pub use for clean public API
  318. - [`proj-prelude-module`](rules/proj-prelude-module.md) - Create prelude module for common imports
  319. - [`proj-bin-dir`](rules/proj-bin-dir.md) - Put multiple binaries in src/bin/
  320. - [`proj-workspace-large`](rules/proj-workspace-large.md) - Use workspaces for large projects
  321. - [`proj-workspace-deps`](rules/proj-workspace-deps.md) - Use workspace dependency inheritance for consistent versions across crates
  322. - [`proj-feature-additive`](rules/proj-feature-additive.md) - Design Cargo features to be strictly additive
  323. - [`proj-msrv-declare`](rules/proj-msrv-declare.md) - Declare `rust-version` (MSRV) in Cargo.toml and test it in CI
  324. - [`proj-build-rs-minimal`](rules/proj-build-rs-minimal.md) - Keep `build.rs` minimal, deterministic, and idempotent
  325. ### 25. Clippy & Linting (LOW)
  326. - [`lint-deny-correctness`](rules/lint-deny-correctness.md) - `#![deny(clippy::correctness)]`
  327. - [`lint-warn-suspicious`](rules/lint-warn-suspicious.md) - Enable clippy::suspicious for likely bugs
  328. - [`lint-warn-style`](rules/lint-warn-style.md) - Enable clippy::style for idiomatic code
  329. - [`lint-warn-complexity`](rules/lint-warn-complexity.md) - Enable clippy::complexity for simpler code
  330. - [`lint-warn-perf`](rules/lint-warn-perf.md) - Enable clippy::perf for performance improvements
  331. - [`lint-pedantic-selective`](rules/lint-pedantic-selective.md) - Enable clippy::pedantic selectively
  332. - [`lint-missing-docs`](rules/lint-missing-docs.md) - Warn on missing documentation for public items
  333. - [`lint-unsafe-doc`](rules/lint-unsafe-doc.md) - Require documentation for unsafe blocks
  334. - [`lint-cargo-metadata`](rules/lint-cargo-metadata.md) - Enable clippy::cargo for published crates
  335. - [`lint-rustfmt-check`](rules/lint-rustfmt-check.md) - Run cargo fmt --check in CI
  336. - [`lint-workspace-lints`](rules/lint-workspace-lints.md) - Configure lints at workspace level for consistent enforcement
  337. - [`lint-cfg-check`](rules/lint-cfg-check.md) - Enable `unexpected_cfgs` and declare known cfgs to catch feature-gate typos
  338. - [`lint-clippy-nursery-selected`](rules/lint-clippy-nursery-selected.md) - Enable high-value `clippy::nursery` lints selectively, not the whole group
  339. ### 26. Anti-patterns (REFERENCE)
  340. - [`anti-unwrap-abuse`](rules/anti-unwrap-abuse.md) - Don't use `.unwrap()` in production code
  341. - [`anti-expect-lazy`](rules/anti-expect-lazy.md) - Don't use expect for recoverable errors
  342. - [`anti-clone-excessive`](rules/anti-clone-excessive.md) - Don't clone when borrowing works
  343. - [`anti-lock-across-await`](rules/anti-lock-across-await.md) - Don't hold locks across await points
  344. - [`anti-string-for-str`](rules/anti-string-for-str.md) - Don't accept &String when &str works
  345. - [`anti-vec-for-slice`](rules/anti-vec-for-slice.md) - Don't accept &Vec<T> when &[T] works
  346. - [`anti-index-over-iter`](rules/anti-index-over-iter.md) - Don't use indexing when iterators work
  347. - [`anti-panic-expected`](rules/anti-panic-expected.md) - Don't panic on expected or recoverable errors
  348. - [`anti-empty-catch`](rules/anti-empty-catch.md) - Don't silently ignore errors
  349. - [`anti-over-abstraction`](rules/anti-over-abstraction.md) - Don't over-abstract with excessive generics
  350. - [`anti-premature-optimize`](rules/anti-premature-optimize.md) - Don't optimize before profiling
  351. - [`anti-type-erasure`](rules/anti-type-erasure.md) - Don't use Box<dyn Trait> when impl Trait works
  352. - [`anti-format-hot-path`](rules/anti-format-hot-path.md) - Don't use format! in hot paths
  353. - [`anti-collect-intermediate`](rules/anti-collect-intermediate.md) - Don't collect intermediate iterators
  354. - [`anti-stringly-typed`](rules/anti-stringly-typed.md) - Don't use strings where enums or newtypes would provide type safety
  355. ---
  356. ## Recommended Cargo.toml Settings
  357. ```toml
  358. [profile.release]
  359. opt-level = 3
  360. lto = "fat"
  361. codegen-units = 1
  362. panic = "abort"
  363. strip = true
  364. [profile.bench]
  365. inherits = "release"
  366. debug = true
  367. strip = false
  368. [profile.dev]
  369. opt-level = 0
  370. debug = true
  371. [profile.dev.package."*"]
  372. opt-level = 3 # Optimize dependencies in dev
  373. ```
  374. ---
  375. ## How to Use
  376. This skill provides rule identifiers for quick reference. When generating or reviewing Rust code:
  377. 1. **Check relevant category** based on task type
  378. 2. **Apply rules** with matching prefix
  379. 3. **Prioritize** CRITICAL > HIGH > MEDIUM > LOW
  380. 4. **Read rule files** in `rules/` for detailed examples
  381. ### Rule Application by Task
  382. | Task | Primary Categories |
  383. |------|-------------------|
  384. | New function | `own-`, `err-`, `name-`, `pat-` |
  385. | New struct/API | `api-`, `type-`, `conv-`, `doc-` |
  386. | Async code | `async-`, `own-` |
  387. | Concurrency / parallelism | `conc-`, `async-`, `own-` |
  388. | Unsafe code | `unsafe-`, `type-`, `test-` |
  389. | Error handling | `err-`, `api-`, `pat-` |
  390. | Type conversions | `conv-`, `api-` |
  391. | Serialization (serde) | `serde-`, `type-`, `api-` |
  392. | Numeric / arithmetic | `num-`, `type-` |
  393. | Macros / code generation | `macro-`, `anti-` |
  394. | Closures / callbacks | `closure-`, `type-` |
  395. | Logging / observability | `obs-`, `err-` |
  396. | Memory optimization | `mem-`, `own-`, `perf-` |
  397. | Performance tuning | `opt-`, `mem-`, `perf-` |
  398. | Code review | `anti-`, `lint-` |
  399. ---
  400. ## Sources & Attribution
  401. This skill is an independent synthesis of official Rust guidance, well-known books, and patterns from widely-used crates. It is not affiliated with or endorsed by the Rust project or any crate author; the text and code examples are original.
  402. **Official Rust documentation**
  403. - [The Rust Reference](https://doc.rust-lang.org/reference/)
  404. - [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/)
  405. - [The Rustonomicon](https://doc.rust-lang.org/nomicon/) (unsafe code)
  406. - [Rust 2024 Edition Guide](https://doc.rust-lang.org/edition-guide/rust-2024/)
  407. - [The Cargo Book](https://doc.rust-lang.org/cargo/)
  408. - [Standard library docs](https://doc.rust-lang.org/std/) and [release notes](https://doc.rust-lang.org/releases.html)
  409. **Books & guides**
  410. - [The Rust Performance Book](https://nnethercote.github.io/perf-book/) — Nicholas Nethercote
  411. - [Rust Design Patterns](https://rust-unofficial.github.io/patterns/) — rust-unofficial
  412. - [Rust Atomics and Locks](https://marabos.nl/atomics/) — Mara Bos
  413. - [Effective Rust](https://effective-rust.com/) — David Drysdale
  414. **Tooling**
  415. - [Clippy lint documentation](https://rust-lang.github.io/rust-clippy/)
  416. - [Miri](https://github.com/rust-lang/miri)
  417. **Real-world codebases studied for idioms**
  418. - ripgrep, tokio, serde, clap, polars, axum, cargo, hyper, bevy, rayon, and dtolnay's crates (thiserror, anyhow, syn)
  419. This project is MIT-licensed. Referenced upstream materials remain under their own licenses (the official Rust docs and API Guidelines are dual MIT / Apache-2.0).
README.md · README · 302 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # Rust Skills
  2. ![rules](https://img.shields.io/badge/rules-265-blue)
  3. ![categories](https://img.shields.io/badge/categories-26-blue)
  4. ![Rust](https://img.shields.io/badge/Rust-1.96%20%2F%202024%20edition-orange)
  5. ![license](https://img.shields.io/badge/license-MIT-green)
  6. 265 Rust rules your AI coding agent can use to write better code. Current for Rust 1.96 (2024 edition).
  7. Works with Claude Code, Cursor, Windsurf, Copilot, Codex, Aider, Zed, Amp, Cline, and pretty much any other agent that supports skills.
  8. ## Why
  9. Out of the box, coding agents write *average* Rust — they clone to dodge the borrow checker, `.unwrap()` everything, and reach for `Box<dyn Trait>` when `impl Trait` would do. These rules encode what expert Rust actually looks like: idiomatic, fast, and safe. Each rule is small and focused, so the agent pulls in only what's relevant to the code in front of it.
  10. ## Install
  11. ```bash
  12. npx add-skill leonardomso/rust-skills
  13. ```
  14. That's it. The CLI figures out which agents you have and installs the skill to the right place.
  15. ## How to use it
  16. After installing, just ask your agent:
  17. ```
  18. /rust-skills review this function
  19. ```
  20. ```
  21. /rust-skills is my error handling idiomatic?
  22. ```
  23. ```
  24. /rust-skills check for memory issues
  25. ```
  26. ```
  27. /rust-skills is this unsafe block sound?
  28. ```
  29. The agent loads the relevant rules and applies them to your code.
  30. ## See it in action
  31. Ask the agent to review a function like this:
  32. ```rust
  33. // before
  34. fn first_word(s: &String) -> String {
  35. s.clone().split_whitespace().next().unwrap().to_string()
  36. }
  37. ```
  38. With these rules loaded, it knows to take `&str` instead of `&String`, drop the
  39. needless `clone()` and allocation, and return an `Option` instead of panicking:
  40. ```rust
  41. // after — applies own-slice-over-vec, own-borrow-over-clone, anti-unwrap-abuse
  42. fn first_word(s: &str) -> Option<&str> {
  43. s.split_whitespace().next()
  44. }
  45. ```
  46. ## What's in here
  47. 265 rules split into 26 categories:
  48. | Category | Rules | What it covers |
  49. |----------|-------|----------------|
  50. | **Ownership & Borrowing** | 12 | When to borrow vs clone, Arc/Rc, lifetimes |
  51. | **Error Handling** | 12 | thiserror for libs, anyhow for apps, the `?` operator |
  52. | **Memory** | 17 | SmallVec, arenas, avoiding allocations, `mem::take`, drop order |
  53. | **Unsafe Code** | 7 | `SAFETY:` comments, Miri, `MaybeUninit`, 2024-edition unsafe |
  54. | **API Design** | 17 | Builder pattern, newtypes, sealed traits, `FromIterator` |
  55. | **Async** | 18 | Tokio patterns, channels, async fn in traits, cancel safety |
  56. | **Concurrency** | 4 | rayon, scoped threads, atomic ordering, thread-locals |
  57. | **Optimization** | 12 | LTO, inlining, PGO, SIMD |
  58. | **Numeric & Arithmetic** | 5 | Overflow handling, `as` vs `TryFrom`, float compare, `NonZero` |
  59. | **Type Safety** | 13 | Newtypes, parse don't validate, `Deref`, `Display`/`Debug` |
  60. | **Trait & Generics Design** | 6 | dyn vs generic, associated types, blanket impls, object safety, orphan rule |
  61. | **Conversions** | 3 | `TryFrom`, `FromStr`, `AsMut` |
  62. | **Const & Compile-Time** | 4 | `const fn`, const vs static, const generics, `const {}` blocks |
  63. | **Serde** | 8 | rename_all, default, flatten, enum tagging, validate-on-deserialize |
  64. | **Pattern Matching** | 5 | `let-else`, `matches!`, if-let chains, exhaustive matches |
  65. | **Macros** | 8 | `macro_rules!` hygiene, fragment specifiers, proc-macros with syn/quote |
  66. | **Closures** | 5 | Fn/FnMut/FnOnce bounds, returning `impl Fn`, move & disjoint capture |
  67. | **Collections** | 4 | HashMap/BTreeMap/IndexMap, Vec/VecDeque, sets, `BinaryHeap` |
  68. | **Naming** | 16 | Following Rust API Guidelines |
  69. | **Testing** | 15 | Proptest, mockall, criterion, loom, snapshot tests |
  70. | **Docs** | 12 | Doc examples, intra-doc links, README/crate-doc unification |
  71. | **Observability** | 7 | tracing over log, spans, structured fields, redacting secrets |
  72. | **Performance** | 13 | Iterators, entry API, faster hashers, I/O buffering |
  73. | **Project Structure** | 14 | Workspaces, module layout, features, MSRV |
  74. | **Linting** | 13 | Clippy config, CI setup, `unexpected_cfgs` |
  75. | **Anti-patterns** | 15 | Common mistakes and how to fix them |
  76. Each rule has:
  77. - Why it matters
  78. - A bad code example
  79. - A good code example
  80. - Links to related rules and sources
  81. ## How it works
  82. The design is built for low token cost and easy auditing:
  83. - **[`SKILL.md`](./SKILL.md)** is a lightweight index — every rule listed as a one-line summary, grouped by category, with a link to its file. The agent reads this first.
  84. - **[`rules/`](./rules)** holds one Markdown file per rule (`<prefix>-<name>.md`). The agent opens only the handful relevant to your code instead of loading all 218 — progressive disclosure keeps context small.
  85. - **Prefixes** (`own-`, `err-`, `unsafe-`, `async-`, …) map directly to categories, so an agent reviewing async code can pull just `async-`, `conc-`, and `own-` rules.
  86. `CLAUDE.md` and `AGENTS.md` are symlinks to `SKILL.md`, so the same content works across agent conventions.
  87. ## Manual install
  88. If `add-skill` doesn't work for your setup, here's how to install manually:
  89. <details>
  90. <summary><b>Claude Code</b></summary>
  91. Global (applies to all projects):
  92. ```bash
  93. git clone https://github.com/leonardomso/rust-skills.git ~/.claude/skills/rust-skills
  94. ```
  95. Or just for one project:
  96. ```bash
  97. git clone https://github.com/leonardomso/rust-skills.git .claude/skills/rust-skills
  98. ```
  99. </details>
  100. <details>
  101. <summary><b>OpenCode</b></summary>
  102. ```bash
  103. git clone https://github.com/leonardomso/rust-skills.git .opencode/skills/rust-skills
  104. ```
  105. </details>
  106. <details>
  107. <summary><b>Cursor</b></summary>
  108. ```bash
  109. git clone https://github.com/leonardomso/rust-skills.git .cursor/skills/rust-skills
  110. ```
  111. Or just grab the skill file:
  112. ```bash
  113. curl -o .cursorrules https://raw.githubusercontent.com/leonardomso/rust-skills/master/SKILL.md
  114. ```
  115. </details>
  116. <details>
  117. <summary><b>Windsurf</b></summary>
  118. ```bash
  119. mkdir -p .windsurf/rules
  120. curl -o .windsurf/rules/rust-skills.md https://raw.githubusercontent.com/leonardomso/rust-skills/master/SKILL.md
  121. ```
  122. </details>
  123. <details>
  124. <summary><b>OpenAI Codex</b></summary>
  125. ```bash
  126. git clone https://github.com/leonardomso/rust-skills.git .codex/skills/rust-skills
  127. ```
  128. Or use the AGENTS.md standard:
  129. ```bash
  130. curl -o AGENTS.md https://raw.githubusercontent.com/leonardomso/rust-skills/master/SKILL.md
  131. ```
  132. </details>
  133. <details>
  134. <summary><b>GitHub Copilot</b></summary>
  135. ```bash
  136. mkdir -p .github
  137. curl -o .github/copilot-instructions.md https://raw.githubusercontent.com/leonardomso/rust-skills/master/SKILL.md
  138. ```
  139. </details>
  140. <details>
  141. <summary><b>Aider</b></summary>
  142. Add to `.aider.conf.yml`:
  143. ```yaml
  144. read: path/to/rust-skills/SKILL.md
  145. ```
  146. Or pass it directly:
  147. ```bash
  148. aider --read path/to/rust-skills/SKILL.md
  149. ```
  150. </details>
  151. <details>
  152. <summary><b>Zed</b></summary>
  153. ```bash
  154. curl -o AGENTS.md https://raw.githubusercontent.com/leonardomso/rust-skills/master/SKILL.md
  155. ```
  156. </details>
  157. <details>
  158. <summary><b>Amp</b></summary>
  159. ```bash
  160. git clone https://github.com/leonardomso/rust-skills.git .agents/skills/rust-skills
  161. ```
  162. </details>
  163. <details>
  164. <summary><b>Cline / Roo Code</b></summary>
  165. ```bash
  166. mkdir -p .clinerules
  167. curl -o .clinerules/rust-skills.md https://raw.githubusercontent.com/leonardomso/rust-skills/master/SKILL.md
  168. ```
  169. </details>
  170. <details>
  171. <summary><b>Other agents (AGENTS.md)</b></summary>
  172. If your agent supports the [AGENTS.md](https://agents.md) standard:
  173. ```bash
  174. curl -o AGENTS.md https://raw.githubusercontent.com/leonardomso/rust-skills/master/SKILL.md
  175. ```
  176. </details>
  177. ## All rules
  178. See [SKILL.md](./SKILL.md) for the full list with links to each rule file.
  179. ## Sources & attribution
  180. These rules are an independent synthesis of official Rust guidance, well-known books, and patterns drawn from widely-used open-source crates. They are not affiliated with or endorsed by the Rust project or any crate author. The text and code examples are original summaries — no substantial content is copied from the sources below.
  181. **Official Rust documentation**
  182. - [The Rust Reference](https://doc.rust-lang.org/reference/)
  183. - [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/)
  184. - [The Rustonomicon](https://doc.rust-lang.org/nomicon/) (unsafe code)
  185. - [Rust 2024 Edition Guide](https://doc.rust-lang.org/edition-guide/rust-2024/)
  186. - [The Cargo Book](https://doc.rust-lang.org/cargo/)
  187. - [Standard library docs](https://doc.rust-lang.org/std/) and [release notes](https://doc.rust-lang.org/releases.html)
  188. **Books & guides**
  189. - [The Rust Performance Book](https://nnethercote.github.io/perf-book/) — Nicholas Nethercote
  190. - [Rust Design Patterns](https://rust-unofficial.github.io/patterns/) — rust-unofficial
  191. - [Rust Atomics and Locks](https://marabos.nl/atomics/) — Mara Bos
  192. - [Effective Rust](https://effective-rust.com/) — David Drysdale
  193. **Tooling**
  194. - [Clippy lint documentation](https://rust-lang.github.io/rust-clippy/)
  195. - [Miri](https://github.com/rust-lang/miri)
  196. **Real-world codebases studied for idioms**
  197. - ripgrep, tokio, serde, clap, polars, axum, cargo, hyper, bevy, rayon, and dtolnay's crates (thiserror, anyhow, syn)
  198. This project is MIT-licensed. Referenced upstream materials remain under their own licenses — the official Rust documentation and API Guidelines are dual [MIT](https://github.com/rust-lang/rust/blob/master/LICENSE-MIT) / [Apache-2.0](https://github.com/rust-lang/rust/blob/master/LICENSE-APACHE).
  199. ## Contributing
  200. PRs welcome. To add or change a rule:
  201. 1. Create `rules/<prefix>-<name>.md` using a `kebab-case` id with an existing category prefix (`own-`, `err-`, `mem-`, …).
  202. 2. Follow the format of existing rules: a `>` one-line summary, then `## Why It Matters`, `## Bad`, `## Good`, and `## See Also` (with links that resolve).
  203. 3. Make sure code examples compile on current stable Rust.
  204. 4. Add the rule to the index in `SKILL.md` (Quick Reference list + the category count) so it stays in sync.
  205. ````markdown
  206. # prefix-rule-name
  207. > One-line imperative summary.
  208. ## Why It Matters
  209. Two to four sentences.
  210. ## Bad
  211. ```rust
  212. // the anti-pattern
  213. ```
  214. ## Good
  215. ```rust
  216. // the recommended pattern
  217. ```
  218. ## See Also
  219. - [other-rule](other-rule.md) - why it's related
  220. ````
  221. ## License
  222. MIT

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.