agentleFS
KalarisLabsKalarisLabs/Skill-Doctor/skills/rust-skills/SKILL.md

rust-skills

Skill13 starsChanged 3 months agoApache-2.0View on GitHub

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.

4 other projects use a version of this, 4 of them edited.

Adopted by

Most recently taken up by

The file

Files
SKILL.md

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)

  • own-borrow-over-clone - Prefer &T borrowing over .clone()
  • own-slice-over-vec - Accept &[T] not &Vec<T>, &str not &String
  • 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> instead of panicking for recoverable errors
  • err-context-chain - Add context with .context() or .with_context()
  • err-no-unwrap-prod - Avoid unwrap() in production code; use ?, expect(), or handle errors
  • err-expect-bugs-only - Use expect() only for invariants that indicate bugs, not user errors
  • 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-doc-errors - Document error conditions with # Errors section in doc comments
  • 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 - Avoid format!() when string literals work
  • mem-write-over-format - Use write!() into existing buffers instead of format!() allocations
  • 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

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)

  • async-tokio-runtime - Configure Tokio runtime appropriately for your workload
  • async-no-lock-await - Never hold Mutex/RwLock across .await
  • 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 spawn

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.