rust-skills by leonardomso/rust-skills
npx skills add https://github.com/leonardomso/rust-skills --skill rust-skills编写高质量、地道且高度优化的 Rust 代码的综合指南。包含 14 个类别共 179 条规则,按影响优先级排序,用于指导 LLM 进行代码生成和重构。
在以下情况下参考这些指南:
| 优先级 | 类别 | 影响 | 前缀 | 规则数 |
|---|---|---|---|---|
| 1 | 所有权与借用 | 关键 | own- | 12 |
| 2 | 错误处理 | 关键 | err- | 12 |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
| 3 | 内存优化 | 关键 | mem- | 15 |
| 4 | API 设计 | 高 | api- | 15 |
| 5 | 异步/等待 | 高 | async- | 15 |
| 6 | 编译器优化 | 高 | opt- | 12 |
| 7 | 命名约定 | 中 | name- | 16 |
| 8 | 类型安全 | 中 | type- | 10 |
| 9 | 测试 | 中 | test- | 13 |
| 10 | 文档 | 中 | doc- | 11 |
| 11 | 性能模式 | 中 | perf- | 11 |
| 12 | 项目结构 | 低 | proj- | 11 |
| 13 | Clippy 与代码检查 | 低 | lint- | 11 |
| 14 | 反模式 | 参考 | anti- | 15 |
own-borrow-over-clone - 优先使用 &T 借用而非 .clone()own-slice-over-vec - 接受 &[T] 而非 &Vec<T>,接受 &str 而非 &Stringown-cow-conditional - 使用 Cow<'a, T> 处理条件所有权own-arc-shared - 使用 Arc<T> 实现线程安全的共享所有权own-rc-single-thread - 使用 Rc<T> 实现单线程共享own-refcell-interior - 使用 RefCell<T> 实现内部可变性(单线程)own-mutex-interior - 使用 Mutex<T> 实现内部可变性(多线程)own-rwlock-readers - 当读操作远多于写操作时使用 RwLock<T>own-copy-small - 为小型、简单的类型派生 Copyown-clone-explicit - 显式使用 Clone,避免隐式复制own-move-large - 移动大型数据而非克隆own-lifetime-elision - 尽可能依赖生命周期省略err-thiserror-lib - 使用 thiserror 处理库的错误类型err-anyhow-app - 使用 anyhow 处理应用程序错误err-result-over-panic - 返回 Result,不要对预期错误使用 panicerr-context-chain - 使用 .context() 或 .with_context() 添加上下文err-no-unwrap-prod - 切勿在生产代码中使用 .unwrap()err-expect-bugs-only - 仅对编程错误使用 .expect()err-question-mark - 使用 ? 操作符进行简洁的错误传播err-from-impl - 使用 #[from] 实现自动错误转换err-source-chain - 使用 #[source] 链接底层错误err-lowercase-msg - 错误信息:小写,无末尾标点err-doc-errors - 使用 # Errors 部分记录错误err-custom-type - 创建自定义错误类型,而非 Box<dyn Error>mem-with-capacity - 当大小已知时使用 with_capacity()mem-smallvec - 对通常较小的集合使用 SmallVecmem-arrayvec - 对有界大小的集合使用 ArrayVecmem-box-large-variant - 装箱大型枚举变体以减少类型大小mem-boxed-slice - 当大小固定时,使用 Box<[T]> 而非 Vec<T>mem-thinvec - 对经常为空的向量使用 ThinVecmem-clone-from - 使用 clone_from() 重用分配mem-reuse-collections - 在循环中使用 clear() 重用集合mem-avoid-format - 当字符串字面量可用时,避免使用 format!()mem-write-over-format - 使用 write!() 而非 format!()mem-arena-allocator - 对批量分配使用区域分配器mem-zero-copy - 对切片和 Bytes 使用零拷贝模式mem-compact-string - 对小字符串优化使用 CompactStringmem-smaller-integers - 使用能容纳数据的最小整数类型mem-assert-type-size - 断言热点类型大小以防止退化api-builder-pattern - 对复杂构造使用构建器模式api-builder-must-use - 为构建器类型添加 #[must_use]api-newtype-safety - 使用新类型实现类型安全的区分api-typestate - 对编译时状态机使用类型状态api-sealed-trait - 密封特征以防止外部实现api-extension-trait - 使用扩展特征为外部类型添加方法api-parse-dont-validate - 在边界处解析为已验证类型api-impl-into - 接受 impl Into<T> 以实现灵活的字符串输入api-impl-asref - 接受 impl AsRef<T> 以实现借用输入api-must-use - 为返回 Result 的函数添加 #[must_use]api-non-exhaustive - 对面向未来的枚举/结构体使用 #[non_exhaustive]api-from-not-into - 实现 From,而非 Into(自动派生)api-default-impl - 为合理的默认值实现 Defaultapi-common-traits - 积极实现 Debug、Clone、PartialEqapi-serde-optional - 将 Serialize/Deserialize 置于特性标志之后async-tokio-runtime - 在生产环境中使用 Tokio 作为异步运行时async-no-lock-await - 切勿在 .await 期间持有 Mutex/RwLockasync-spawn-blocking - 对 CPU 密集型工作使用 spawn_blockingasync-tokio-fs - 在异步代码中使用 tokio::fs 而非 std::fsasync-cancellation-token - 使用 CancellationToken 实现优雅关闭async-join-parallel - 对并行操作使用 tokio::join!async-try-join - 对可能失败的并行操作使用 tokio::try_join!async-select-racing - 对竞态/超时使用 tokio::select!async-bounded-channel - 对背压使用有界通道async-mpsc-queue - 对工作队列使用 mpscasync-broadcast-pubsub - 对发布/订阅模式使用 broadcastasync-watch-latest - 对最新值共享使用 watchasync-oneshot-response - 对请求/响应使用 oneshotasync-joinset-structured - 对动态任务组使用 JoinSetasync-clone-before-await - 在 await 前克隆数据,释放锁opt-inline-small - 对小型热点函数使用 #[inline]opt-inline-always-rare - 谨慎使用 #[inline(always)]opt-inline-never-cold - 对冷路径使用 #[inline(never)]opt-cold-unlikely - 对错误/不太可能的路径使用 #[cold]opt-likely-hint - 对分支提示使用 likely()/unlikely()opt-lto-release - 在发布版本中启用 LTOopt-codegen-units - 使用 codegen-units = 1 实现最大优化opt-pgo-profile - 对生产构建使用 PGOopt-target-cpu - 为本地构建设置 target-cpu=nativeopt-bounds-check - 使用迭代器以避免边界检查opt-simd-portable - 对数据并行操作使用便携式 SIMDopt-cache-friendly - 设计缓存友好的数据布局(SoA)name-types-camel - 对类型、特征、枚举使用 UpperCamelCasename-variants-camel - 对枚举变体使用 UpperCamelCasename-funcs-snake - 对函数、方法、模块使用 snake_casename-consts-screaming - 对常量/静态变量使用 SCREAMING_SNAKE_CASEname-lifetime-short - 使用简短的小写生命周期:'a、'de、'srcname-type-param-single - 对类型参数使用单个大写字母:T、E、K、Vname-as-free - as_ 前缀:免费引用转换name-to-expensive - to_ 前缀:昂贵的转换name-into-ownership - into_ 前缀:所有权转移name-no-get-prefix - 简单的 getter 方法不加 get_ 前缀name-is-has-bool - 对布尔方法使用 is_、has_、can_name-iter-convention - 对迭代器使用 iter/iter_mut/into_itername-iter-method - 一致地命名迭代器方法name-iter-type-match - 迭代器类型名称与方法匹配name-acronym-word - 将首字母缩写词视为单词:Uuid 而非 UUIDname-crate-no-rs - 包名:不加 -rs 后缀type-newtype-ids - 将 ID 包装在新类型中:UserId(u64)type-newtype-validated - 对已验证数据使用新类型:Email、Urltype-enum-states - 对互斥状态使用枚举type-option-nullable - 对可空值使用 Option<T>type-result-fallible - 对可能失败的操作使用 Result<T, E>type-phantom-marker - 对类型级标记使用 PhantomData<T>type-never-diverge - 对永不返回的函数使用 ! 类型type-generic-bounds - 仅在需要的地方添加特征约束type-no-stringly - 避免字符串类型的 API,使用枚举/新类型type-repr-transparent - 对 FFI 新类型使用 #[repr(transparent)]test-cfg-test-module - 使用 #[cfg(test)] mod tests { }test-use-super - 在测试模块中使用 use super::*;test-integration-dir - 将集成测试放在 tests/ 目录中test-descriptive-names - 使用描述性的测试名称test-arrange-act-assert - 按 arrange/act/assert 结构组织测试test-proptest-properties - 使用 proptest 进行基于属性的测试test-mockall-mocking - 使用 mockall 进行特征模拟test-mock-traits - 对依赖项使用特征以支持模拟test-fixture-raii - 使用 RAII 模式(Drop)进行测试清理test-tokio-async - 对异步测试使用 #[tokio::test]test-should-panic - 对 panic 测试使用 #[should_panic]test-criterion-bench - 使用 criterion 进行基准测试test-doctest-examples - 将文档示例保持为可执行测试doc-all-public - 使用 /// 记录所有公共项doc-module-inner - 使用 //! 进行模块级文档记录doc-examples-section - 包含带有可运行代码的 # Examplesdoc-errors-section - 对可能失败的函数包含 # Errorsdoc-panics-section - 对可能 panic 的函数包含 # Panicsdoc-safety-section - 对 unsafe 函数包含 # Safetydoc-question-mark - 在示例中使用 ?,而非 .unwrap()doc-hidden-setup - 使用 # 前缀隐藏示例设置代码doc-intra-links - 使用文档内链接:[Vec]doc-link-types - 在文档中链接相关类型和函数doc-cargo-metadata - 填写 Cargo.toml 元数据perf-iter-over-index - 优先使用迭代器而非手动索引perf-iter-lazy - 保持迭代器惰性,仅在需要时使用 collect()perf-collect-once - 不要 collect() 中间迭代器perf-entry-api - 对映射的插入或更新使用 entry() APIperf-drain-reuse - 使用 drain() 重用分配perf-extend-batch - 对批量插入使用 extend()perf-chain-avoid - 在热点循环中避免使用 chain()perf-collect-into - 对重用容器使用 collect_into()perf-black-box-bench - 在基准测试中使用 black_box()perf-release-profile - 优化发布配置文件设置perf-profile-first - 先分析,再优化proj-lib-main-split - 保持 main.rs 最小化,逻辑放在 lib.rsproj-mod-by-feature - 按功能而非类型组织模块proj-flat-small - 保持小型项目扁平化proj-mod-rs-dir - 对多文件模块使用 mod.rsproj-pub-crate-internal - 对内部 API 使用 pub(crate)proj-pub-super-parent - 对仅父级可见性使用 pub(super)proj-pub-use-reexport - 使用 pub use 实现清晰的公共 APIproj-prelude-module - 为常用导入创建 prelude 模块proj-bin-dir - 将多个二进制文件放在 src/bin/ 中proj-workspace-large - 对大型项目使用工作区proj-workspace-deps - 使用工作区依赖继承lint-deny-correctness - #![deny(clippy::correctness)]lint-warn-suspicious - #![warn(clippy::suspicious)]lint-warn-style](https://github.com/leonardomso/rust-skills/blob/HEAD/rules/lint-warnComprehensive 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.
Reference these guidelines when:
| 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 |
own-borrow-over-clone - Prefer &T borrowing over .clone()own-slice-over-vec - Accept &[T] not &Vec<T>, &str not &Stringown-cow-conditional - Use for conditional ownershiperr-thiserror-lib - Use thiserror for library error typeserr-anyhow-app - Use anyhow for application error handlingerr-result-over-panic - Return Result, don't panic on expected errorserr-context-chain - Add context with .context() or mem-with-capacity - Use with_capacity() when size is knownmem-smallvec - Use SmallVec for usually-small collectionsmem-arrayvec - Use ArrayVec for bounded-size collectionsmem-box-large-variant - Box large enum variants to reduce type sizeapi-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 implementationsasync-tokio-runtime - Use Tokio for production async runtimeasync-no-lock-await - Never hold Mutex/RwLock across .awaitasync-spawn-blocking - Use spawn_blocking for CPU-intensive workasync-tokio-fs - Use not in async codeopt-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 pathsname-types-camel - Use UpperCamelCase for types, traits, enumsname-variants-camel - Use UpperCamelCase for enum variantsname-funcs-snake - Use snake_case for functions, methods, modulesname-consts-screaming - Use SCREAMING_SNAKE_CASE for constants/staticstype-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 - Use Option<T> for nullable valuestest-cfg-test-module - Use #[cfg(test)] mod tests { }test-use-super - Use use super::*; in test modulestest-integration-dir - Put integration tests in tests/ directorytest-descriptive-names - Use descriptive test namesdoc-all-public - Document all public items with ///doc-module-inner - Use //! for module-level documentationdoc-examples-section - Include # Examples with runnable codedoc-errors-section - Include # Errors for fallible functionsperf-iter-over-index - Prefer iterators over manual indexingperf-iter-lazy - Keep iterators lazy, collect() only when neededperf-collect-once - Don't collect() intermediate iteratorsperf-entry-api - Use entry() API for map insert-or-updateperf-drain-reuse - Use to reuse allocationsproj-lib-main-split - Keep main.rs minimal, logic in lib.rsproj-mod-by-feature - Organize modules by feature, not typeproj-flat-small - Keep small projects flatproj-mod-rs-dir - Use mod.rs for multi-file modulesproj-pub-crate-internal - Use for internal APIslint-deny-correctness - #![deny(clippy::correctness)]lint-warn-suspicious - #![warn(clippy::suspicious)]lint-warn-style - #![warn(clippy::style)]lint-warn-complexity - #![warn(clippy::complexity)]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 .await[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
This skill provides rule identifiers for quick reference. When generating or reviewing Rust code:
rules/ for detailed examples| Task | Primary Categories |
|---|---|
| New function | own-, err-, name- |
| New struct/API | api-, type-, doc- |
| Async code | async-, own- |
| Error handling | , |
This skill synthesizes best practices from:
Weekly Installs
411
Repository
GitHub Stars
103
First Seen
Jan 20, 2026
Security Audits
Gen Agent Trust HubFailSocketPassSnykWarn
Installed on
opencode364
codex353
gemini-cli346
github-copilot335
kimi-cli302
amp301
Swift Actor 线程安全持久化:构建离线优先应用的编译器强制安全数据层
1,200 周安装
Cow<'a, T>own-arc-shared - Use Arc<T> for thread-safe shared ownershipown-rc-single-thread - Use Rc<T> for single-threaded sharingown-refcell-interior - Use RefCell<T> for interior mutability (single-thread)own-mutex-interior - Use Mutex<T> for interior mutability (multi-thread)own-rwlock-readers - Use RwLock<T> when reads dominate writesown-copy-small - Derive Copy for small, trivial typesown-clone-explicit - Make Clone explicit, avoid implicit copiesown-move-large - Move large data instead of cloningown-lifetime-elision - Rely on lifetime elision when possible.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 # Errors sectionerr-custom-type - Create custom error types, not Box<dyn Error>mem-boxed-sliceBox<[T]>Vec<T>mem-thinvec - Use ThinVec for often-empty vectorsmem-clone-from - Use clone_from() to reuse allocationsmem-reuse-collections - Reuse collections with clear() in loopsmem-avoid-format - Avoid format!() when string literals workmem-write-over-format - Use write!() instead of format!()mem-arena-allocator - Use arena allocators for batch allocationsmem-zero-copy - Use zero-copy patterns with slices and Bytesmem-compact-string - Use CompactString for small string optimizationmem-smaller-integers - Use smallest integer type that fitsmem-assert-type-size - Assert hot type sizes to prevent regressionsapi-extension-traitapi-parse-dont-validate - Parse into validated types at boundariesapi-impl-into - Accept impl Into<T> for flexible string inputsapi-impl-asref - Accept impl AsRef<T> for borrowed inputsapi-must-use - Add #[must_use] to Result returning functionsapi-non-exhaustive - Use #[non_exhaustive] for future-proof enums/structsapi-from-not-into - Implement From, not Into (auto-derived)api-default-impl - Implement Default for sensible defaultsapi-common-traits - Implement Debug, Clone, PartialEq eagerlyapi-serde-optional - Gate Serialize/Deserialize behind feature flagtokio::fsstd::fsasync-cancellation-token - Use CancellationToken for graceful shutdownasync-join-parallel - Use tokio::join! for parallel operationsasync-try-join - Use tokio::try_join! for fallible parallel opsasync-select-racing - Use tokio::select! for racing/timeoutsasync-bounded-channel - Use bounded channels for backpressureasync-mpsc-queue - Use mpsc for work queuesasync-broadcast-pubsub - Use broadcast for pub/sub patternsasync-watch-latest - Use watch for latest-value sharingasync-oneshot-response - Use oneshot for request/responseasync-joinset-structured - Use JoinSet for dynamic task groupsasync-clone-before-await - Clone data before await, release locksopt-likely-hint - Use likely()/unlikely() for branch hintsopt-lto-release - Enable LTO in release buildsopt-codegen-units - Use codegen-units = 1 for max optimizationopt-pgo-profile - Use PGO for production buildsopt-target-cpu - Set target-cpu=native for 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)name-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 - No get_ prefix for simple gettersname-is-has-bool - Use is_, has_, can_ for boolean methodsname-iter-convention - Use iter/iter_mut/into_iter for iteratorsname-iter-method - Name iterator methods consistentlyname-iter-type-match - Iterator type names match methodname-acronym-word - Treat acronyms as words: Uuid not UUIDname-crate-no-rs - Crate names: no -rs suffixtype-result-fallible - Use Result<T, E> for fallible operationstype-phantom-marker - Use PhantomData<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 newtypestest-arrange-act-asserttest-proptest-properties - Use proptest for property-based testingtest-mockall-mocking - Use mockall for 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 - Use criterion for benchmarkingtest-doctest-examples - Keep doc examples as executable testsdoc-panics-section - Include # Panics for panicking functionsdoc-safety-section - Include # Safety for 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 - Fill Cargo.toml metadatadrain()perf-extend-batch - Use extend() for batch insertionsperf-chain-avoid - Avoid chain() in hot loopsperf-collect-into - Use collect_into() for reusing containersperf-black-box-bench - Use black_box() in benchmarksperf-release-profile - Optimize release profile settingsperf-profile-first - Profile before optimizingpub(crate)proj-pub-super-parent - Use pub(super) for parent-only visibilityproj-pub-use-reexport - Use pub use for clean public APIproj-prelude-module - Create prelude module for common importsproj-bin-dir - Put multiple binaries in src/bin/proj-workspace-large - Use workspaces for large projectsproj-workspace-deps - Use workspace dependency inheritancelint-warn-perf - #![warn(clippy::perf)]lint-pedantic-selective - Enable clippy::pedantic selectivelylint-missing-docs - #![warn(missing_docs)]lint-unsafe-doc - #![warn(clippy::undocumented_unsafe_blocks)]lint-cargo-metadata - #![warn(clippy::cargo)] for published crateslint-rustfmt-check - Run cargo fmt --check in CIlint-workspace-lints - Configure lints at workspace levelanti-string-for-str&String&stranti-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 empty if let Err(_) = ... blocksanti-over-abstraction - Don't over-abstract with excessive genericsanti-premature-optimize - Don't optimize before profilinganti-type-erasure - Don't use Box<dyn Trait> when impl Trait worksanti-format-hot-path - Don't use format!() in hot pathsanti-collect-intermediate - Don't collect() intermediate iteratorsanti-stringly-typed - Don't use strings for structured dataerr-api-| Memory optimization | mem-, own-, perf- |
| Performance tuning | opt-, mem-, perf- |
| Code review | anti-, lint- |