Claude-skill-registry rust-skills
install
source · Clone the upstream repo
git clone https://github.com/majiayu000/claude-skill-registry
Claude Code · Install into ~/.claude/skills/
T=$(mktemp -d) && git clone --depth=1 https://github.com/majiayu000/claude-skill-registry "$T" && mkdir -p ~/.claude/skills && cp -r "$T/skills/other/other/rust-skills" ~/.claude/skills/majiayu000-claude-skill-registry-rust-skills && rm -rf "$T"
manifest:
skills/other/other/rust-skills/SKILL.mdsource content
Rust Best Practices
Comprehensive guide for writing high-quality, idiomatic, and highly optimized Rust code. Contains 179 rules across 14 categories, prioritized by impact to guide LLMs in code generation and refactoring.
When to Apply
Reference these guidelines when:
- Writing new Rust functions, structs, or modules
- Implementing error handling or async 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 | | 12 |
| 2 | Error Handling | CRITICAL | | 12 |
| 3 | Memory Optimization | CRITICAL | | 15 |
| 4 | API Design | HIGH | | 15 |
| 5 | Async/Await | HIGH | | 15 |
| 6 | Compiler Optimization | HIGH | | 12 |
| 7 | Naming Conventions | MEDIUM | | 16 |
| 8 | Type Safety | MEDIUM | | 10 |
| 9 | Testing | MEDIUM | | 13 |
| 10 | Documentation | MEDIUM | | 11 |
| 11 | Performance Patterns | MEDIUM | | 11 |
| 12 | Project Structure | LOW | | 11 |
| 13 | Clippy & Linting | LOW | | 11 |
| 14 | Anti-patterns | REFERENCE | | 15 |
Quick Reference
1. Ownership & Borrowing (CRITICAL)
- Preferown-borrow-over-clone
borrowing over&T.clone()
- Acceptown-slice-over-vec
not&[T]
,&Vec<T>
not&str&String
- Useown-cow-conditional
for conditional ownershipCow<'a, T>
- Useown-arc-shared
for thread-safe shared ownershipArc<T>
- Useown-rc-single-thread
for single-threaded sharingRc<T>
- Useown-refcell-interior
for interior mutability (single-thread)RefCell<T>
- Useown-mutex-interior
for interior mutability (multi-thread)Mutex<T>
- Useown-rwlock-readers
when reads dominate writesRwLock<T>
- Deriveown-copy-small
for small, trivial typesCopy
- Makeown-clone-explicit
explicit, avoid implicit copiesClone
- Move large data instead of cloningown-move-large
- Rely on lifetime elision when possibleown-lifetime-elision
2. Error Handling (CRITICAL)
- Useerr-thiserror-lib
for library error typesthiserror
- Useerr-anyhow-app
for application error handlinganyhow
- Returnerr-result-over-panic
, don't panic on expected errorsResult
- Add context witherr-context-chain
or.context().with_context()
- Never useerr-no-unwrap-prod
in production code.unwrap()
- Useerr-expect-bugs-only
only for programming errors.expect()
- Useerr-question-mark
operator for clean propagation?
- Useerr-from-impl
for automatic error conversion#[from]
- Useerr-source-chain
to chain underlying errors#[source]
- Error messages: lowercase, no trailing punctuationerr-lowercase-msg
- Document errors witherr-doc-errors
section# Errors
- Create custom error types, noterr-custom-typeBox<dyn Error>
3. Memory Optimization (CRITICAL)
- Usemem-with-capacity
when size is knownwith_capacity()
- Usemem-smallvec
for usually-small collectionsSmallVec
- Usemem-arrayvec
for bounded-size collectionsArrayVec
- Box large enum variants to reduce type sizemem-box-large-variant
- Usemem-boxed-slice
instead ofBox<[T]>
when fixedVec<T>
- Usemem-thinvec
for often-empty vectorsThinVec
- Usemem-clone-from
to reuse allocationsclone_from()
- Reuse collections withmem-reuse-collections
in loopsclear()
- Avoidmem-avoid-format
when string literals workformat!()
- Usemem-write-over-format
instead ofwrite!()format!()
- Use arena allocators for batch allocationsmem-arena-allocator
- Use zero-copy patterns with slices andmem-zero-copyBytes
- Usemem-compact-string
for small string optimizationCompactString
- Use smallest integer type that fitsmem-smaller-integers
- Assert hot type sizes to prevent regressionsmem-assert-type-size
4. API Design (HIGH)
- Use Builder pattern for complex constructionapi-builder-pattern
- Addapi-builder-must-use
to builder types#[must_use]
- Use newtypes for type-safe distinctionsapi-newtype-safety
- Use typestate for compile-time state machinesapi-typestate
- Seal traits to prevent external implementationsapi-sealed-trait
- Use extension traits to add methods to foreign typesapi-extension-trait
- Parse into validated types at boundariesapi-parse-dont-validate
- Acceptapi-impl-into
for flexible string inputsimpl Into<T>
- Acceptapi-impl-asref
for borrowed inputsimpl AsRef<T>
- Addapi-must-use
to#[must_use]
returning functionsResult
- Useapi-non-exhaustive
for future-proof enums/structs#[non_exhaustive]
- Implementapi-from-not-into
, notFrom
(auto-derived)Into
- Implementapi-default-impl
for sensible defaultsDefault
- Implementapi-common-traits
,Debug
,Clone
eagerlyPartialEq
- Gateapi-serde-optional
/Serialize
behind feature flagDeserialize
5. Async/Await (HIGH)
- Use Tokio for production async runtimeasync-tokio-runtime
- Never holdasync-no-lock-await
/Mutex
acrossRwLock.await
- Useasync-spawn-blocking
for CPU-intensive workspawn_blocking
- Useasync-tokio-fs
nottokio::fs
in async codestd::fs
- Useasync-cancellation-token
for graceful shutdownCancellationToken
- Useasync-join-parallel
for parallel operationstokio::join!
- Useasync-try-join
for fallible parallel opstokio::try_join!
- Useasync-select-racing
for racing/timeoutstokio::select!
- Use bounded channels for backpressureasync-bounded-channel
- Useasync-mpsc-queue
for work queuesmpsc
- Useasync-broadcast-pubsub
for pub/sub patternsbroadcast
- Useasync-watch-latest
for latest-value sharingwatch
- Useasync-oneshot-response
for request/responseoneshot
- Useasync-joinset-structured
for dynamic task groupsJoinSet
- Clone data before await, release locksasync-clone-before-await
6. Compiler Optimization (HIGH)
- Useopt-inline-small
for small hot functions#[inline]
- Useopt-inline-always-rare
sparingly#[inline(always)]
- Useopt-inline-never-cold
for cold paths#[inline(never)]
- Useopt-cold-unlikely
for error/unlikely paths#[cold]
- Useopt-likely-hint
/likely()
for branch hintsunlikely()
- Enable LTO in release buildsopt-lto-release
- Useopt-codegen-units
for max optimizationcodegen-units = 1
- Use PGO for production buildsopt-pgo-profile
- Setopt-target-cpu
for local buildstarget-cpu=native
- Use iterators to avoid bounds checksopt-bounds-check
- Use portable SIMD for data-parallel opsopt-simd-portable
- Design cache-friendly data layouts (SoA)opt-cache-friendly
7. Naming Conventions (MEDIUM)
- Usename-types-camel
for types, traits, enumsUpperCamelCase
- Usename-variants-camel
for enum variantsUpperCamelCase
- Usename-funcs-snake
for functions, methods, modulessnake_case
- Usename-consts-screaming
for constants/staticsSCREAMING_SNAKE_CASE
- Use short lowercase lifetimes:name-lifetime-short
,'a
,'de'src
- Use single uppercase for type params:name-type-param-single
,T
,E
,KV
-name-as-free
prefix: free reference conversionas_
-name-to-expensive
prefix: expensive conversionto_
-name-into-ownership
prefix: ownership transferinto_
- Noname-no-get-prefix
prefix for simple gettersget_
- Usename-is-has-bool
,is_
,has_
for boolean methodscan_
- Usename-iter-convention
/iter
/iter_mut
for iteratorsinto_iter
- Name iterator methods consistentlyname-iter-method
- Iterator type names match methodname-iter-type-match
- Treat acronyms as words:name-acronym-word
notUuidUUID
- Crate names: noname-crate-no-rs
suffix-rs
8. Type Safety (MEDIUM)
- Wrap IDs in newtypes:type-newtype-idsUserId(u64)
- Newtypes for validated data:type-newtype-validated
,EmailUrl
- Use enums for mutually exclusive statestype-enum-states
- Usetype-option-nullable
for nullable valuesOption<T>
- Usetype-result-fallible
for fallible operationsResult<T, E>
- Usetype-phantom-marker
for type-level markersPhantomData<T>
- Usetype-never-diverge
type for functions that never return!
- Add trait bounds only where neededtype-generic-bounds
- Avoid stringly-typed APIs, use enums/newtypestype-no-stringly
- Usetype-repr-transparent
for FFI newtypes#[repr(transparent)]
9. Testing (MEDIUM)
- Usetest-cfg-test-module#[cfg(test)] mod tests { }
- Usetest-use-super
in test modulesuse super::*;
- Put integration tests intest-integration-dir
directorytests/
- Use descriptive test namestest-descriptive-names
- Structure tests as arrange/act/asserttest-arrange-act-assert
- Usetest-proptest-properties
for property-based testingproptest
- Usetest-mockall-mocking
for trait mockingmockall
- Use traits for dependencies to enable mockingtest-mock-traits
- Use RAII pattern (Drop) for test cleanuptest-fixture-raii
- Usetest-tokio-async
for async tests#[tokio::test]
- Usetest-should-panic
for panic tests#[should_panic]
- Usetest-criterion-bench
for benchmarkingcriterion
- Keep doc examples as executable teststest-doctest-examples
10. Documentation (MEDIUM)
- Document all public items withdoc-all-public///
- Usedoc-module-inner
for module-level documentation//!
- Includedoc-examples-section
with runnable code# Examples
- Includedoc-errors-section
for fallible functions# Errors
- Includedoc-panics-section
for panicking functions# Panics
- Includedoc-safety-section
for unsafe functions# Safety
- Usedoc-question-mark
in examples, not?.unwrap()
- Usedoc-hidden-setup
prefix to hide example setup code#
- Use intra-doc links:doc-intra-links[Vec]
- Link related types and functions in docsdoc-link-types
- Filldoc-cargo-metadata
metadataCargo.toml
11. Performance Patterns (MEDIUM)
- Prefer iterators over manual indexingperf-iter-over-index
- Keep iterators lazy, collect() only when neededperf-iter-lazy
- Don'tperf-collect-once
intermediate iteratorscollect()
- Useperf-entry-api
API for map insert-or-updateentry()
- Useperf-drain-reuse
to reuse allocationsdrain()
- Useperf-extend-batch
for batch insertionsextend()
- Avoidperf-chain-avoid
in hot loopschain()
- Useperf-collect-into
for reusing containerscollect_into()
- Useperf-black-box-bench
in benchmarksblack_box()
- Optimize release profile settingsperf-release-profile
- Profile before optimizingperf-profile-first
12. Project Structure (LOW)
- Keepproj-lib-main-split
minimal, logic inmain.rslib.rs
- Organize modules by feature, not typeproj-mod-by-feature
- Keep small projects flatproj-flat-small
- Useproj-mod-rs-dir
for multi-file modulesmod.rs
- Useproj-pub-crate-internal
for internal APIspub(crate)
- Useproj-pub-super-parent
for parent-only visibilitypub(super)
- Useproj-pub-use-reexport
for clean public APIpub use
- Createproj-prelude-module
module for common importsprelude
- Put multiple binaries inproj-bin-dirsrc/bin/
- Use workspaces for large projectsproj-workspace-large
- Use workspace dependency inheritanceproj-workspace-deps
13. Clippy & Linting (LOW)
-lint-deny-correctness#![deny(clippy::correctness)]
-lint-warn-suspicious#![warn(clippy::suspicious)]
-lint-warn-style#![warn(clippy::style)]
-lint-warn-complexity#![warn(clippy::complexity)]
-lint-warn-perf#![warn(clippy::perf)]
- Enablelint-pedantic-selective
selectivelyclippy::pedantic
-lint-missing-docs#![warn(missing_docs)]
-lint-unsafe-doc#![warn(clippy::undocumented_unsafe_blocks)]
-lint-cargo-metadata
for published crates#![warn(clippy::cargo)]
- Runlint-rustfmt-check
in CIcargo fmt --check
- Configure lints at workspace levellint-workspace-lints
14. Anti-patterns (REFERENCE)
- Don't useanti-unwrap-abuse
in production code.unwrap()
- Don't useanti-expect-lazy
for recoverable errors.expect()
- Don't clone when borrowing worksanti-clone-excessive
- Don't hold locks acrossanti-lock-across-await.await
- Don't acceptanti-string-for-str
when&String
works&str
- Don't acceptanti-vec-for-slice
when&Vec<T>
works&[T]
- Don't use indexing when iterators workanti-index-over-iter
- Don't panic on expected/recoverable errorsanti-panic-expected
- Don't use emptyanti-empty-catch
blocksif let Err(_) = ...
- Don't over-abstract with excessive genericsanti-over-abstraction
- Don't optimize before profilinganti-premature-optimize
- Don't useanti-type-erasure
whenBox<dyn Trait>
worksimpl Trait
- Don't useanti-format-hot-path
in hot pathsformat!()
- Don'tanti-collect-intermediate
intermediate iteratorscollect()
- Don't use strings for structured dataanti-stringly-typed
Recommended Cargo.toml Settings
Standalone project
[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
Workspace
[workspace] members = ["crates/*"] resolver = "2" [workspace.package] edition = "2024" rust-version = "1.85" license = "MIT" [workspace.dependencies] # Pin shared dependencies here tokio = { version = "1", features = ["full"] } serde = { version = "1", features = ["derive"] } thiserror = "2" anyhow = "1" [workspace.lints.rust] unsafe_code = "forbid" [workspace.lints.clippy] correctness = { level = "deny", priority = -1 } suspicious = { level = "warn", priority = -1 } style = { level = "warn", priority = -1 } complexity = { level = "warn", priority = -1 } perf = { level = "warn", priority = -1 } pedantic = { level = "warn", priority = -1 } [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
Member crates inherit from the workspace:
[package] name = "my-crate" version = "0.1.0" edition.workspace = true rust-version.workspace = true license.workspace = true [dependencies] tokio = { workspace = true } serde = { workspace = true } [lints] workspace = true
How to Use
This skill provides rule identifiers for quick reference. When generating or reviewing Rust code:
- Check relevant category based on task type
- Apply rules with matching prefix
- Prioritize CRITICAL > HIGH > MEDIUM > LOW
- Read rule files in
for detailed examplesrules/
Rule Application by Task
| Task | Primary Categories |
|---|---|
| New function | , , |
| New struct/API | , , |
| Async code | , |
| Error handling | , |
| Memory optimization | , , |
| Performance tuning | , , |
| Code review | , |
Sources
This skill synthesizes best practices from:
- Rust API Guidelines
- Rust Performance Book
- Rust Design Patterns
- Production codebases: ripgrep, tokio, serde, polars, axum, deno
- Clippy lint documentation
- Community conventions (2024-2025)