leonardomso/rust-skills

rust-skills

Comprehensive Rust coding guidelines with 265 rules across 26 categories.

Ver código fuente
Documento original del Skill

Contenido del repositorio de origen con títulos, ejemplos, código, tablas, enlaces e imágenes preservados.

Rust Best Practices

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).

When to Apply

Reference these guidelines when:

  • Writing new Rust functions, structs, or modules
  • Implementing error handling or async code
  • Writing concurrent, parallel, or unsafe code
  • Designing public APIs for libraries
  • Reviewing code for ownership/borrowing issues
  • Optimizing memory usage or reducing allocations
  • Tuning performance for hot paths
  • Refactoring existing Rust code

Rule Categories by Priority

PriorityCategoryImpactPrefixRules
1Ownership & BorrowingCRITICALown-12
2Error HandlingCRITICALerr-12
3Memory OptimizationCRITICALmem-17
4Unsafe CodeCRITICALunsafe-7
5API DesignHIGHapi-17
6Async/AwaitHIGHasync-18
7ConcurrencyHIGHconc-4
8Compiler OptimizationHIGHopt-12
9Numeric & Arithmetic SafetyHIGHnum-5
10Type SafetyMEDIUMtype-13
11Trait & Generics DesignMEDIUMtrait-6
12ConversionsMEDIUMconv-3
13Const & Compile-TimeMEDIUMconst-4
14SerdeMEDIUMserde-8
15Pattern MatchingMEDIUMpat-5
16MacrosMEDIUMmacro-8
17ClosuresMEDIUMclosure-5
18CollectionsMEDIUMcoll-4
19Naming ConventionsMEDIUMname-16
20TestingMEDIUMtest-15
21DocumentationMEDIUMdoc-12
22ObservabilityMEDIUMobs-7
23Performance PatternsMEDIUMperf-13
24Project StructureLOWproj-14
25Clippy & LintingLOWlint-13
26Anti-patternsREFERENCEanti-15

Quick Reference

1. Ownership & Borrowing (CRITICAL)

2. Error Handling (CRITICAL)

3. Memory Optimization (CRITICAL)

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.

5. API Design (HIGH)

6. Async/Await (HIGH)

7. Concurrency (HIGH)

8. Compiler Optimization (HIGH)

9. Numeric & Arithmetic Safety (HIGH)

10. Type Safety (MEDIUM)

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` - Choose static dispatch (generics / impl Trait) vs dynamic dispatch (dyn Trait) deliberately
  • `trait-object-safety` - Keep a trait dyn-compatible (object-safe) when you need dyn Trait

12. Conversions (MEDIUM)

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)

15. Pattern Matching (MEDIUM)

16. Macros (MEDIUM)

17. Closures (MEDIUM)

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)

20. Testing (MEDIUM)

21. Documentation (MEDIUM)

22. Observability (MEDIUM)

23. Performance Patterns (MEDIUM)

24. Project Structure (LOW)

25. Clippy & Linting (LOW)

26. Anti-patterns (REFERENCE)


Recommended Cargo.toml Settings

toml
[profile.release]
opt-level = 3
lto = "fat"
codegen-units = 1
panic = "abort"
strip = true

[profile.bench]
inherits = "release"
debug = true
strip = false

[profile.dev]
opt-level = 0
debug = true

[profile.dev.package."*"]
opt-level = 3  # Optimize dependencies in dev

How to Use

This skill provides rule identifiers for quick reference. When generating or reviewing Rust code:

  1. Check relevant category based on task type
  2. Apply rules with matching prefix
  3. Prioritize CRITICAL > HIGH > MEDIUM > LOW
  4. Read rule files in rules/ for detailed examples

Rule Application by Task

TaskPrimary Categories
New functionown-, err-, name-, pat-
New struct/APIapi-, type-, conv-, doc-
Async codeasync-, own-
Concurrency / parallelismconc-, async-, own-
Unsafe codeunsafe-, type-, test-
Error handlingerr-, api-, pat-
Type conversionsconv-, api-
Serialization (serde)serde-, type-, api-
Numeric / arithmeticnum-, type-
Macros / code generationmacro-, anti-
Closures / callbacksclosure-, type-
Logging / observabilityobs-, err-
Memory optimizationmem-, own-, perf-
Performance tuningopt-, mem-, perf-
Code reviewanti-, lint-

Sources & Attribution

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.

Official Rust documentation

Books & guides

Tooling

Real-world codebases studied for idioms

  • ripgrep, tokio, serde, clap, polars, axum, cargo, hyper, bevy, rayon, and dtolnay's crates (thiserror, anyhow, syn)

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).