rust-skills
122
总安装量
122
周安装量
#1935
全站排名
安装命令
npx skills add https://github.com/leonardomso/rust-skills --skill rust-skills
Agent 安装分布
opencode
86
claude-code
78
codex
75
gemini-cli
72
github-copilot
63
cursor
50
Skill 文档
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 | own- |
12 |
| 2 | Error Handling | CRITICAL | err- |
12 |
| 3 | Memory Optimization | CRITICAL | mem- |
15 |
| 4 | API Design | HIGH | api- |
15 |
| 5 | Async/Await | HIGH | async- |
15 |
| 6 | Compiler Optimization | HIGH | opt- |
12 |
| 7 | Naming Conventions | MEDIUM | name- |
16 |
| 8 | Type Safety | MEDIUM | type- |
10 |
| 9 | Testing | MEDIUM | test- |
13 |
| 10 | Documentation | MEDIUM | doc- |
11 |
| 11 | Performance Patterns | MEDIUM | perf- |
11 |
| 12 | Project Structure | LOW | proj- |
11 |
| 13 | Clippy & Linting | LOW | lint- |
11 |
| 14 | Anti-patterns | REFERENCE | anti- |
15 |
Quick Reference
1. Ownership & Borrowing (CRITICAL)
own-borrow-over-clone– Prefer&Tborrowing over.clone()own-slice-over-vec– Accept&[T]not&Vec<T>,&strnot&Stringown-cow-conditional– UseCow<'a, T>for conditional ownershipown-arc-shared– UseArc<T>for thread-safe shared ownershipown-rc-single-thread– UseRc<T>for single-threaded sharingown-refcell-interior– UseRefCell<T>for interior mutability (single-thread)own-mutex-interior– UseMutex<T>for interior mutability (multi-thread)own-rwlock-readers– UseRwLock<T>when reads dominate writesown-copy-small– DeriveCopyfor small, trivial typesown-clone-explicit– MakeCloneexplicit, avoid implicit copiesown-move-large– Move large data instead of cloningown-lifetime-elision– Rely on lifetime elision when possible
2. Error Handling (CRITICAL)
err-thiserror-lib– Usethiserrorfor library error typeserr-anyhow-app– Useanyhowfor application error handlingerr-result-over-panic– ReturnResult, don’t panic on expected errorserr-context-chain– Add context with.context()or.with_context()err-no-unwrap-prod– Never use.unwrap()in production codeerr-expect-bugs-only– Use.expect()only for programming errorserr-question-mark– Use?operator for clean propagationerr-from-impl– Use#[from]for automatic error conversionerr-source-chain– Use#[source]to chain underlying errorserr-lowercase-msg– Error messages: lowercase, no trailing punctuationerr-doc-errors– Document errors with# Errorssectionerr-custom-type– Create custom error types, notBox<dyn Error>
3. Memory Optimization (CRITICAL)
mem-with-capacity– Usewith_capacity()when size is knownmem-smallvec– UseSmallVecfor usually-small collectionsmem-arrayvec– UseArrayVecfor bounded-size collectionsmem-box-large-variant– Box large enum variants to reduce type sizemem-boxed-slice– UseBox<[T]>instead ofVec<T>when fixedmem-thinvec– UseThinVecfor often-empty vectorsmem-clone-from– Useclone_from()to reuse allocationsmem-reuse-collections– Reuse collections withclear()in loopsmem-avoid-format– Avoidformat!()when string literals workmem-write-over-format– Usewrite!()instead offormat!()mem-arena-allocator– Use arena allocators for batch allocationsmem-zero-copy– Use zero-copy patterns with slices andBytesmem-compact-string– UseCompactStringfor small string optimizationmem-smaller-integers– Use smallest integer type that fitsmem-assert-type-size– Assert hot type sizes to prevent regressions
4. API Design (HIGH)
api-builder-pattern– Use Builder pattern for complex constructionapi-builder-must-use– Add#[must_use]to builder typesapi-newtype-safety– Use newtypes for type-safe distinctionsapi-typestate– Use typestate for compile-time state machinesapi-sealed-trait– Seal traits to prevent external implementationsapi-extension-trait– Use extension traits to add methods to foreign typesapi-parse-dont-validate– Parse into validated types at boundariesapi-impl-into– Acceptimpl Into<T>for flexible string inputsapi-impl-asref– Acceptimpl AsRef<T>for borrowed inputsapi-must-use– Add#[must_use]toResultreturning functionsapi-non-exhaustive– Use#[non_exhaustive]for future-proof enums/structsapi-from-not-into– ImplementFrom, notInto(auto-derived)api-default-impl– ImplementDefaultfor sensible defaultsapi-common-traits– ImplementDebug,Clone,PartialEqeagerlyapi-serde-optional– GateSerialize/Deserializebehind feature flag
5. Async/Await (HIGH)
async-tokio-runtime– Use Tokio for production async runtimeasync-no-lock-await– Never holdMutex/RwLockacross.awaitasync-spawn-blocking– Usespawn_blockingfor CPU-intensive workasync-tokio-fs– Usetokio::fsnotstd::fsin async codeasync-cancellation-token– UseCancellationTokenfor graceful shutdownasync-join-parallel– Usetokio::join!for parallel operationsasync-try-join– Usetokio::try_join!for fallible parallel opsasync-select-racing– Usetokio::select!for racing/timeoutsasync-bounded-channel– Use bounded channels for backpressureasync-mpsc-queue– Usempscfor work queuesasync-broadcast-pubsub– Usebroadcastfor pub/sub patternsasync-watch-latest– Usewatchfor latest-value sharingasync-oneshot-response– Useoneshotfor request/responseasync-joinset-structured– UseJoinSetfor dynamic task groupsasync-clone-before-await– Clone data before await, release locks
6. Compiler Optimization (HIGH)
opt-inline-small– Use#[inline]for small hot functionsopt-inline-always-rare– Use#[inline(always)]sparinglyopt-inline-never-cold– Use#[inline(never)]for cold pathsopt-cold-unlikely– Use#[cold]for error/unlikely pathsopt-likely-hint– Uselikely()/unlikely()for branch hintsopt-lto-release– Enable LTO in release buildsopt-codegen-units– Usecodegen-units = 1for max optimizationopt-pgo-profile– Use PGO for production buildsopt-target-cpu– Settarget-cpu=nativefor local buildsopt-bounds-check– Use iterators to avoid bounds checksopt-simd-portable– Use portable SIMD for data-parallel opsopt-cache-friendly– Design cache-friendly data layouts (SoA)
7. Naming Conventions (MEDIUM)
name-types-camel– UseUpperCamelCasefor types, traits, enumsname-variants-camel– UseUpperCamelCasefor enum variantsname-funcs-snake– Usesnake_casefor functions, methods, modulesname-consts-screaming– UseSCREAMING_SNAKE_CASEfor constants/staticsname-lifetime-short– Use short lowercase lifetimes:'a,'de,'srcname-type-param-single– Use single uppercase for type params:T,E,K,Vname-as-free–as_prefix: free reference conversionname-to-expensive–to_prefix: expensive conversionname-into-ownership–into_prefix: ownership transfername-no-get-prefix– Noget_prefix for simple gettersname-is-has-bool– Useis_,has_,can_for boolean methodsname-iter-convention– Useiter/iter_mut/into_iterfor iteratorsname-iter-method– Name iterator methods consistentlyname-iter-type-match– Iterator type names match methodname-acronym-word– Treat acronyms as words:UuidnotUUIDname-crate-no-rs– Crate names: no-rssuffix
8. Type Safety (MEDIUM)
type-newtype-ids– Wrap IDs in newtypes:UserId(u64)type-newtype-validated– Newtypes for validated data:Email,Urltype-enum-states– Use enums for mutually exclusive statestype-option-nullable– UseOption<T>for nullable valuestype-result-fallible– UseResult<T, E>for fallible operationstype-phantom-marker– UsePhantomData<T>for type-level markerstype-never-diverge– Use!type for functions that never returntype-generic-bounds– Add trait bounds only where neededtype-no-stringly– Avoid stringly-typed APIs, use enums/newtypestype-repr-transparent– Use#[repr(transparent)]for FFI newtypes
9. Testing (MEDIUM)
test-cfg-test-module– Use#[cfg(test)] mod tests { }test-use-super– Useuse super::*;in test modulestest-integration-dir– Put integration tests intests/directorytest-descriptive-names– Use descriptive test namestest-arrange-act-assert– Structure tests as arrange/act/asserttest-proptest-properties– Useproptestfor property-based testingtest-mockall-mocking– Usemockallfor trait mockingtest-mock-traits– Use traits for dependencies to enable mockingtest-fixture-raii– Use RAII pattern (Drop) for test cleanuptest-tokio-async– Use#[tokio::test]for async teststest-should-panic– Use#[should_panic]for panic teststest-criterion-bench– Usecriterionfor benchmarkingtest-doctest-examples– Keep doc examples as executable tests
10. Documentation (MEDIUM)
doc-all-public– Document all public items with///doc-module-inner– Use//!for module-level documentationdoc-examples-section– Include# Exampleswith runnable codedoc-errors-section– Include# Errorsfor fallible functionsdoc-panics-section– Include# Panicsfor panicking functionsdoc-safety-section– Include# Safetyfor unsafe functionsdoc-question-mark– Use?in examples, not.unwrap()doc-hidden-setup– Use#prefix to hide example setup codedoc-intra-links– Use intra-doc links:[Vec]doc-link-types– Link related types and functions in docsdoc-cargo-metadata– FillCargo.tomlmetadata
11. Performance Patterns (MEDIUM)
perf-iter-over-index– Prefer iterators over manual indexingperf-iter-lazy– Keep iterators lazy, collect() only when neededperf-collect-once– Don’tcollect()intermediate iteratorsperf-entry-api– Useentry()API for map insert-or-updateperf-drain-reuse– Usedrain()to reuse allocationsperf-extend-batch– Useextend()for batch insertionsperf-chain-avoid– Avoidchain()in hot loopsperf-collect-into– Usecollect_into()for reusing containersperf-black-box-bench– Useblack_box()in benchmarksperf-release-profile– Optimize release profile settingsperf-profile-first– Profile before optimizing
12. Project Structure (LOW)
proj-lib-main-split– Keepmain.rsminimal, logic inlib.rsproj-mod-by-feature– Organize modules by feature, not typeproj-flat-small– Keep small projects flatproj-mod-rs-dir– Usemod.rsfor multi-file modulesproj-pub-crate-internal– Usepub(crate)for internal APIsproj-pub-super-parent– Usepub(super)for parent-only visibilityproj-pub-use-reexport– Usepub usefor clean public APIproj-prelude-module– Createpreludemodule for common importsproj-bin-dir– Put multiple binaries insrc/bin/proj-workspace-large– Use workspaces for large projectsproj-workspace-deps– Use workspace dependency inheritance
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)]lint-pedantic-selective– Enableclippy::pedanticselectivelylint-missing-docs–#![warn(missing_docs)]lint-unsafe-doc–#![warn(clippy::undocumented_unsafe_blocks)]lint-cargo-metadata–#![warn(clippy::cargo)]for published crateslint-rustfmt-check– Runcargo fmt --checkin CIlint-workspace-lints– Configure lints at workspace level
14. Anti-patterns (REFERENCE)
anti-unwrap-abuse– Don’t use.unwrap()in production codeanti-expect-lazy– Don’t use.expect()for recoverable errorsanti-clone-excessive– Don’t clone when borrowing worksanti-lock-across-await– Don’t hold locks across.awaitanti-string-for-str– Don’t accept&Stringwhen&strworksanti-vec-for-slice– Don’t accept&Vec<T>when&[T]worksanti-index-over-iter– Don’t use indexing when iterators workanti-panic-expected– Don’t panic on expected/recoverable errorsanti-empty-catch– Don’t use emptyif let Err(_) = ...blocksanti-over-abstraction– Don’t over-abstract with excessive genericsanti-premature-optimize– Don’t optimize before profilinganti-type-erasure– Don’t useBox<dyn Trait>whenimpl Traitworksanti-format-hot-path– Don’t useformat!()in hot pathsanti-collect-intermediate– Don’tcollect()intermediate iteratorsanti-stringly-typed– Don’t use strings for structured data
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:
- Check relevant category based on task type
- Apply rules with matching prefix
- Prioritize CRITICAL > HIGH > MEDIUM > LOW
- Read rule files in
rules/for detailed examples
Rule Application by Task
| Task | Primary Categories |
|---|---|
| New function | own-, err-, name- |
| New struct/API | api-, type-, doc- |
| Async code | async-, own- |
| Error handling | err-, api- |
| Memory optimization | mem-, own-, perf- |
| Performance tuning | opt-, mem-, perf- |
| Code review | anti-, lint- |
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)