rust-skills

内容来源:SKILL.md(标准 Skill 格式) · 原始地址 · 查看安装指南

原始内容


name: rust-skills description: > 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. license: MIT metadata: author: leonardomso version: "1.5.1" sources: - Rust API Guidelines - Rust Performance Book - Rust 2024 Edition Guide - The Rustonomicon - ripgrep, tokio, serde, polars, axum, cargo codebases


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

Priority Category Impact Prefix Rules
1 Ownership & Borrowing CRITICAL own- 12
2 Error Handling CRITICAL err- 12
3 Memory Optimization CRITICAL mem- 17
4 Unsafe Code CRITICAL unsafe- 7
5 API Design HIGH api- 17
6 Async/Await HIGH async- 18
7 Concurrency HIGH conc- 4
8 Compiler Optimization HIGH opt- 12
9 Numeric & Arithmetic Safety HIGH num- 5
10 Type Safety MEDIUM type- 13
11 Trait & Generics Design MEDIUM trait- 6
12 Conversions MEDIUM conv- 3
13 Const & Compile-Time MEDIUM const- 4
14 Serde MEDIUM serde- 8
15 Pattern Matching MEDIUM pat- 5
16 Macros MEDIUM macro- 8
17 Closures MEDIUM closure- 5
18 Collections MEDIUM coll- 4
19 Naming Conventions MEDIUM name- 16
20 Testing MEDIUM test- 15
21 Documentation MEDIUM doc- 12
22 Observability MEDIUM obs- 7
23 Performance Patterns MEDIUM perf- 13
24 Project Structure LOW proj- 14
25 Clippy & Linting LOW lint- 13
26 Anti-patterns REFERENCE anti- 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)

  • 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

6. Async/Await (HIGH)

7. Concurrency (HIGH)

8. Compiler Optimization (HIGH)

9. Numeric & Arithmetic Safety (HIGH)

  • num-overflow-explicit - Handle integer overflow explicitly: checked_/saturating_/wrapping_/overflowing_
  • num-cast-try-from - Avoid as for narrowing casts; use From for widening and TryFrom for narrowing
  • num-float-compare - Don't compare floats with ==; use a tolerance, and total_cmp for ordering
  • 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)

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)

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

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)

  • 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 - Never log secrets or PII; redact or skip them

23. Performance Patterns (MEDIUM)

24. Project Structure (LOW)

25. Clippy & Linting (LOW)

26. Anti-patterns (REFERENCE)


Recommended Cargo.toml Settings

[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

Task Primary Categories
New function own-, err-, name-, pat-
New struct/API api-, type-, conv-, doc-
Async code async-, own-
Concurrency / parallelism conc-, async-, own-
Unsafe code unsafe-, type-, test-
Error handling err-, api-, pat-
Type conversions conv-, api-
Serialization (serde) serde-, type-, api-
Numeric / arithmetic num-, type-
Macros / code generation macro-, anti-
Closures / callbacks closure-, type-
Logging / observability obs-, err-
Memory optimization mem-, own-, perf-
Performance tuning opt-, mem-, perf-
Code review anti-, 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).