rust-skills
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRust Best Practices
Rust 最佳实践
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.
本指南是编写高质量、符合Rust风格且高度优化的Rust代码的综合参考,包含14个分类下的179条规则,按影响优先级排序,可指导大语言模型进行代码生成与重构。
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
在以下场景中可参考本指南:
- 编写新的Rust函数、结构体或模块
- 实现错误处理或异步代码
- 设计库的公共API
- 评审代码中的所有权/借用问题
- 优化内存使用或减少内存分配
- 调优热点路径的性能
- 重构现有Rust代码
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 |
| 优先级 | 分类 | 影响等级 | 前缀 | 规则数量 |
|---|---|---|---|---|
| 1 | 所有权与借用 | 严重 | | 12 |
| 2 | 错误处理 | 严重 | | 12 |
| 3 | 内存优化 | 严重 | | 15 |
| 4 | API设计 | 高 | | 15 |
| 5 | Async/Await | 高 | | 15 |
| 6 | 编译器优化 | 高 | | 12 |
| 7 | 命名规范 | 中 | | 16 |
| 8 | 类型安全 | 中 | | 10 |
| 9 | 测试 | 中 | | 13 |
| 10 | 文档 | 中 | | 11 |
| 11 | 性能模式 | 中 | | 11 |
| 12 | 项目结构 | 低 | | 11 |
| 13 | Clippy与代码检查 | 低 | | 11 |
| 14 | 反模式 | 参考 | | 15 |
Quick Reference
快速参考
1. Ownership & Borrowing (CRITICAL)
1. 所有权与借用(严重)
- - Prefer
own-borrow-over-cloneborrowing over&T.clone() - - Accept
own-slice-over-vecnot&[T],&Vec<T>not&str&String - - Use
own-cow-conditionalfor conditional ownershipCow<'a, T> - - Use
own-arc-sharedfor thread-safe shared ownershipArc<T> - - Use
own-rc-single-threadfor single-threaded sharingRc<T> - - Use
own-refcell-interiorfor interior mutability (single-thread)RefCell<T> - - Use
own-mutex-interiorfor interior mutability (multi-thread)Mutex<T> - - Use
own-rwlock-readerswhen reads dominate writesRwLock<T> - - Derive
own-copy-smallfor small, trivial typesCopy - - Make
own-clone-explicitexplicit, avoid implicit copiesClone - - Move large data instead of cloning
own-move-large - - Rely on lifetime elision when possible
own-lifetime-elision
- - 优先使用
own-borrow-over-clone借用而非&T.clone() - - 接收
own-slice-over-vec而非&[T],接收&Vec<T>而非&str&String - - 对条件性所有权场景使用
own-cow-conditionalCow<'a, T> - - 对线程安全的共享所有权使用
own-arc-sharedArc<T> - - 对单线程场景的共享使用
own-rc-single-threadRc<T> - - 对单线程内部可变性使用
own-refcell-interiorRefCell<T> - - 对多线程内部可变性使用
own-mutex-interiorMutex<T> - - 当读操作远多于写操作时使用
own-rwlock-readersRwLock<T> - - 为小型、简单类型派生
own-copy-smalltraitCopy - - 显式使用
own-clone-explicit,避免隐式复制Clone - - 移动大型数据而非克隆
own-move-large - - 尽可能依赖生命周期省略规则
own-lifetime-elision
2. Error Handling (CRITICAL)
2. 错误处理(严重)
- - Use
err-thiserror-libfor library error typesthiserror - - Use
err-anyhow-appfor application error handlinganyhow - - Return
err-result-over-panic, don't panic on expected errorsResult - - Add context with
err-context-chainor.context().with_context() - - Never use
err-no-unwrap-prodin production code.unwrap() - - Use
err-expect-bugs-onlyonly for programming errors.expect() - - Use
err-question-markoperator for clean propagation? - - Use
err-from-implfor automatic error conversion#[from] - - Use
err-source-chainto chain underlying errors#[source] - - Error messages: lowercase, no trailing punctuation
err-lowercase-msg - - Document errors with
err-doc-errorssection# Errors - - Create custom error types, not
err-custom-typeBox<dyn Error>
- - 为库的错误类型使用
err-thiserror-libthiserror - - 为应用的错误处理使用
err-anyhow-appanyhow - - 返回
err-result-over-panic,对预期错误不要panicResult - - 使用
err-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-typeBox<dyn Error>
3. Memory Optimization (CRITICAL)
3. 内存优化(严重)
- - Use
mem-with-capacitywhen size is knownwith_capacity() - - Use
mem-smallvecfor usually-small collectionsSmallVec - - Use
mem-arrayvecfor bounded-size collectionsArrayVec - - Box large enum variants to reduce type size
mem-box-large-variant - - Use
mem-boxed-sliceinstead ofBox<[T]>when fixedVec<T> - - Use
mem-thinvecfor often-empty vectorsThinVec - - Use
mem-clone-fromto reuse allocationsclone_from() - - Reuse collections with
mem-reuse-collectionsin loopsclear() - - Avoid
mem-avoid-formatwhen string literals workformat!() - - Use
mem-write-over-formatinstead ofwrite!()format!() - - Use arena allocators for batch allocations
mem-arena-allocator - - Use zero-copy patterns with slices and
mem-zero-copyBytes - - Use
mem-compact-stringfor small string optimizationCompactString - - Use smallest integer type that fits
mem-smaller-integers - - Assert hot type sizes to prevent regressions
mem-assert-type-size
- - 已知容量时使用
mem-with-capacitywith_capacity() - - 对通常较小的集合使用
mem-smallvecSmallVec - - 对有界大小的集合使用
mem-arrayvecArrayVec - - 对大型枚举变体使用Box包裹以减少类型大小
mem-box-large-variant - - 固定大小场景下使用
mem-boxed-slice而非Box<[T]>Vec<T> - - 对经常为空的向量使用
mem-thinvecThinVec - - 使用
mem-clone-from复用内存分配clone_from() - - 在循环中使用
mem-reuse-collections复用集合clear() - - 能用字符串字面量时避免使用
mem-avoid-formatformat!() - - 使用
mem-write-over-format替代write!()format!() - - 批量分配场景下使用内存池分配器
mem-arena-allocator - - 使用切片和
mem-zero-copy实现零拷贝模式Bytes - - 对小型字符串使用
mem-compact-string优化CompactString - - 使用能容纳数据的最小整数类型
mem-smaller-integers - - 断言热点类型的大小以防止性能退化
mem-assert-type-size
4. API Design (HIGH)
4. API设计(高)
- - Use Builder pattern for complex construction
api-builder-pattern - - Add
api-builder-must-useto builder types#[must_use] - - Use newtypes for type-safe distinctions
api-newtype-safety - - Use typestate for compile-time state machines
api-typestate - - Seal traits to prevent external implementations
api-sealed-trait - - Use extension traits to add methods to foreign types
api-extension-trait - - Parse into validated types at boundaries
api-parse-dont-validate - - Accept
api-impl-intofor flexible string inputsimpl Into<T> - - Accept
api-impl-asreffor borrowed inputsimpl AsRef<T> - - Add
api-must-useto#[must_use]returning functionsResult - - Use
api-non-exhaustivefor future-proof enums/structs#[non_exhaustive] - - Implement
api-from-not-into, notFrom(auto-derived)Into - - Implement
api-default-implfor sensible defaultsDefault - - Implement
api-common-traits,Debug,CloneeagerlyPartialEq - - Gate
api-serde-optional/Serializebehind feature flagDeserialize
- - 复杂构造场景使用构建器模式
api-builder-pattern - - 为构建器类型添加
api-builder-must-use属性#[must_use] - - 使用新类型实现类型安全的区分
api-newtype-safety - - 使用类型状态实现编译时状态机
api-typestate - - 密封trait以防止外部实现
api-sealed-trait - - 使用扩展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会自动派生)Into - - 为合理的默认值实现
api-default-impltraitDefault - - 尽早实现
api-common-traits、Debug、Clone等通用traitPartialEq - - 将
api-serde-optional/Serialize放在feature flag后Deserialize
5. Async/Await (HIGH)
5. Async/Await(高)
- - Use Tokio for production async runtime
async-tokio-runtime - - Never hold
async-no-lock-await/MutexacrossRwLock.await - - Use
async-spawn-blockingfor CPU-intensive workspawn_blocking - - Use
async-tokio-fsnottokio::fsin async codestd::fs - - Use
async-cancellation-tokenfor graceful shutdownCancellationToken - - Use
async-join-parallelfor parallel operationstokio::join! - - Use
async-try-joinfor fallible parallel opstokio::try_join! - - Use
async-select-racingfor racing/timeoutstokio::select! - - Use bounded channels for backpressure
async-bounded-channel - - Use
async-mpsc-queuefor work queuesmpsc - - Use
async-broadcast-pubsubfor pub/sub patternsbroadcast - - Use
async-watch-latestfor latest-value sharingwatch - - Use
async-oneshot-responsefor request/responseoneshot - - Use
async-joinset-structuredfor dynamic task groupsJoinSet - - Clone data before await, release locks
async-clone-before-await
- - 生产环境异步代码使用Tokio运行时
async-tokio-runtime - - 绝不要在
async-no-lock-await期间持有.await/Mutex锁RwLock - - CPU密集型任务使用
async-spawn-blockingspawn_blocking - - 异步代码中使用
async-tokio-fs而非tokio::fsstd::fs - - 使用
async-cancellation-token实现优雅关闭CancellationToken - - 并行操作使用
async-join-paralleltokio::join! - - 可能失败的并行操作使用
async-try-jointokio::try_join! - - 竞争/超时场景使用
async-select-racingtokio::select! - - 使用有界通道实现背压
async-bounded-channel - - 工作队列场景使用
async-mpsc-queuempsc - - 发布/订阅模式使用
async-broadcast-pubsubbroadcast - - 最新值共享场景使用
async-watch-latestwatch - - 请求/响应场景使用
async-oneshot-responseoneshot - - 动态任务组使用
async-joinset-structuredJoinSet - - 在await前克隆数据,释放锁
async-clone-before-await
6. Compiler Optimization (HIGH)
6. 编译器优化(高)
- - Use
opt-inline-smallfor small hot functions#[inline] - - Use
opt-inline-always-raresparingly#[inline(always)] - - Use
opt-inline-never-coldfor cold paths#[inline(never)] - - Use
opt-cold-unlikelyfor error/unlikely paths#[cold] - - Use
opt-likely-hint/likely()for branch hintsunlikely() - - Enable LTO in release builds
opt-lto-release - - Use
opt-codegen-unitsfor max optimizationcodegen-units = 1 - - Use PGO for production builds
opt-pgo-profile - - Set
opt-target-cpufor local buildstarget-cpu=native - - Use iterators to avoid bounds checks
opt-bounds-check - - Use portable SIMD for data-parallel ops
opt-simd-portable - - Design cache-friendly data layouts (SoA)
opt-cache-friendly
- - 小型热点函数使用
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() - - 发布构建中启用LTO
opt-lto-release - - 使用
opt-codegen-units以获得最大优化效果codegen-units = 1 - - 生产构建使用PGO(性能引导优化)
opt-pgo-profile - - 本地构建设置
opt-target-cputarget-cpu=native - - 使用迭代器避免边界检查
opt-bounds-check - - 数据并行操作使用可移植SIMD
opt-simd-portable - - 设计缓存友好的数据布局(SoA)
opt-cache-friendly
7. Naming Conventions (MEDIUM)
7. 命名规范(中)
- - Use
name-types-camelfor types, traits, enumsUpperCamelCase - - Use
name-variants-camelfor enum variantsUpperCamelCase - - Use
name-funcs-snakefor functions, methods, modulessnake_case - - Use
name-consts-screamingfor 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-freeprefix: free reference conversionas_ - -
name-to-expensiveprefix: expensive conversionto_ - -
name-into-ownershipprefix: ownership transferinto_ - - No
name-no-get-prefixprefix for simple gettersget_ - - Use
name-is-has-bool,is_,has_for boolean methodscan_ - - Use
name-iter-convention/iter/iter_mutfor iteratorsinto_iter - - Name iterator methods consistently
name-iter-method - - Iterator type names match method
name-iter-type-match - - Treat acronyms as words:
name-acronym-wordnotUuidUUID - - Crate names: no
name-crate-no-rssuffix-rs
- - 类型、trait、枚举使用
name-types-camelUpperCamelCase - - 枚举变体使用
name-variants-camelUpperCamelCase - - 函数、方法、模块使用
name-funcs-snakesnake_case - - 常量/静态变量使用
name-consts-screamingSCREAMING_SNAKE_CASE - - 使用短小写字母作为生命周期名称:
name-lifetime-short、'a、'de'src - - 使用单个大写字母作为类型参数:
name-type-param-single、T、E、KV - - 无代价的引用转换使用
name-as-free前缀as_ - - 高代价转换使用
name-to-expensive前缀to_ - - 所有权转移使用
name-into-ownership前缀into_ - - 简单getter不要使用
name-no-get-prefix前缀get_ - - 布尔方法使用
name-is-has-bool、is_、has_前缀can_ - - 迭代器使用
name-iter-convention/iter/iter_mut命名into_iter - - 迭代器方法命名保持一致
name-iter-method - - 迭代器类型名称与方法名匹配
name-iter-type-match - - 首字母缩写词视为单词:
name-acronym-word而非UuidUUID - - crate名称不要使用
name-crate-no-rs后缀-rs
8. Type Safety (MEDIUM)
8. 类型安全(中)
- - Wrap IDs in newtypes:
type-newtype-idsUserId(u64) - - Newtypes for validated data:
type-newtype-validated,EmailUrl - - Use enums for mutually exclusive states
type-enum-states - - Use
type-option-nullablefor nullable valuesOption<T> - - Use
type-result-falliblefor fallible operationsResult<T, E> - - Use
type-phantom-markerfor type-level markersPhantomData<T> - - Use
type-never-divergetype for functions that never return! - - Add trait bounds only where needed
type-generic-bounds - - Avoid stringly-typed APIs, use enums/newtypes
type-no-stringly - - Use
type-repr-transparentfor FFI newtypes#[repr(transparent)]
- - 使用新类型包裹ID:
type-newtype-idsUserId(u64) - - 使用新类型包裹已验证数据:
type-newtype-validated、EmailUrl - - 互斥状态使用枚举
type-enum-states - - 可空值使用
type-option-nullableOption<T> - - 可能失败的操作使用
type-result-fallibleResult<T, E> - - 类型级别标记使用
type-phantom-markerPhantomData<T> - - 永不返回的函数使用
type-never-diverge类型! - - 仅在需要时添加trait约束
type-generic-bounds - - 避免字符串化API,使用枚举/新类型
type-no-stringly - - FFI场景的新类型使用
type-repr-transparent#[repr(transparent)]
9. Testing (MEDIUM)
9. 测试(中)
- - Use
test-cfg-test-module#[cfg(test)] mod tests { } - - Use
test-use-superin test modulesuse super::*; - - Put integration tests in
test-integration-dirdirectorytests/ - - Use descriptive test names
test-descriptive-names - - Structure tests as arrange/act/assert
test-arrange-act-assert - - Use
test-proptest-propertiesfor property-based testingproptest - - Use
test-mockall-mockingfor trait mockingmockall - - Use traits for dependencies to enable mocking
test-mock-traits - - Use RAII pattern (Drop) for test cleanup
test-fixture-raii - - Use
test-tokio-asyncfor async tests#[tokio::test] - - Use
test-should-panicfor panic tests#[should_panic] - - Use
test-criterion-benchfor benchmarkingcriterion - - Keep doc examples as executable tests
test-doctest-examples
- - 使用
test-cfg-test-module定义测试模块#[cfg(test)] mod tests { } - - 测试模块中使用
test-use-superuse super::*; - - 集成测试放在
test-integration-dir目录下tests/ - - 使用描述性的测试名称
test-descriptive-names - - 测试结构遵循“准备/执行/断言”模式
test-arrange-act-assert - - 属性测试使用
test-proptest-propertiesproptest - - trait mocking使用
test-mockall-mockingmockall - - 依赖项使用trait以支持mock
test-mock-traits - - 测试清理使用RAII模式(Drop trait)
test-fixture-raii - - 异步测试使用
test-tokio-async#[tokio::test] - - panic测试使用
test-should-panic#[should_panic] - - 基准测试使用
test-criterion-benchcriterion - - 文档示例保持可执行性
test-doctest-examples
10. Documentation (MEDIUM)
10. 文档(中)
- - Document all public items with
doc-all-public/// - - Use
doc-module-innerfor module-level documentation//! - - Include
doc-examples-sectionwith runnable code# Examples - - Include
doc-errors-sectionfor fallible functions# Errors - - Include
doc-panics-sectionfor panicking functions# Panics - - Include
doc-safety-sectionfor unsafe functions# Safety - - Use
doc-question-markin examples, not?.unwrap() - - Use
doc-hidden-setupprefix to hide example setup code# - - Use intra-doc links:
doc-intra-links[Vec] - - Link related types and functions in docs
doc-link-types - - Fill
doc-cargo-metadatametadataCargo.toml
- - 使用
doc-all-public为所有公共项编写文档/// - - 使用
doc-module-inner编写模块级文档//! - - 包含
doc-examples-section章节并提供可运行代码# Examples - - 为可能失败的函数添加
doc-errors-section章节# Errors - - 为可能panic的函数添加
doc-panics-section章节# Panics - - 为不安全函数添加
doc-safety-section章节# Safety - - 示例中使用
doc-question-mark而非?.unwrap() - - 使用
doc-hidden-setup前缀隐藏示例中的准备代码# - - 使用文档内链接:
doc-intra-links[Vec] - - 在文档中链接相关类型和函数
doc-link-types - - 完善
doc-cargo-metadata中的元数据Cargo.toml
11. Performance Patterns (MEDIUM)
11. 性能模式(中)
- - Prefer iterators over manual indexing
perf-iter-over-index - - Keep iterators lazy, collect() only when needed
perf-iter-lazy - - Don't
perf-collect-onceintermediate iteratorscollect() - - Use
perf-entry-apiAPI for map insert-or-updateentry() - - Use
perf-drain-reuseto reuse allocationsdrain() - - Use
perf-extend-batchfor batch insertionsextend() - - Avoid
perf-chain-avoidin hot loopschain() - - Use
perf-collect-intofor reusing containerscollect_into() - - Use
perf-black-box-benchin benchmarksblack_box() - - Optimize release profile settings
perf-release-profile - - Profile before optimizing
perf-profile-first
- - 优先使用迭代器而非手动索引
perf-iter-over-index - - 保持迭代器惰性,仅在需要时使用
perf-iter-lazycollect() - - 不要对中间迭代器调用
perf-collect-oncecollect() - - 映射的插入或更新使用
perf-entry-apiAPIentry() - - 使用
perf-drain-reuse复用内存分配drain() - - 批量插入使用
perf-extend-batchextend() - - 热点循环中避免使用
perf-chain-avoidchain() - - 使用
perf-collect-into复用容器collect_into() - - 基准测试中使用
perf-black-box-benchblack_box() - - 优化发布配置文件的设置
perf-release-profile - - 优化前先进行性能分析
perf-profile-first
12. Project Structure (LOW)
12. 项目结构(低)
- - Keep
proj-lib-main-splitminimal, logic inmain.rslib.rs - - Organize modules by feature, not type
proj-mod-by-feature - - Keep small projects flat
proj-flat-small - - Use
proj-mod-rs-dirfor multi-file modulesmod.rs - - Use
proj-pub-crate-internalfor internal APIspub(crate) - - Use
proj-pub-super-parentfor parent-only visibilitypub(super) - - Use
proj-pub-use-reexportfor clean public APIpub use - - Create
proj-prelude-modulemodule for common importsprelude - - Put multiple binaries in
proj-bin-dirsrc/bin/ - - Use workspaces for large projects
proj-workspace-large - - Use workspace dependency inheritance
proj-workspace-deps
- - 保持
proj-lib-main-split简洁,业务逻辑放在main.rs中lib.rs - - 按功能而非类型组织模块
proj-mod-by-feature - - 小型项目保持扁平化结构
proj-flat-small - - 多文件模块使用
proj-mod-rs-dirmod.rs - - 内部API使用
proj-pub-crate-internalpub(crate) - - 仅对父模块可见的API使用
proj-pub-super-parentpub(super) - - 使用
proj-pub-use-reexport构建清晰的公共APIpub use - - 创建
proj-prelude-module模块统一导出常用项prelude - - 多个二进制文件放在
proj-bin-dir目录下src/bin/ - - 大型项目使用工作区
proj-workspace-large - - 工作区中统一管理依赖
proj-workspace-deps
13. Clippy & Linting (LOW)
13. Clippy与代码检查(低)
- -
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)] - - Enable
lint-pedantic-selectiveselectivelyclippy::pedantic - -
lint-missing-docs#![warn(missing_docs)] - -
lint-unsafe-doc#![warn(clippy::undocumented_unsafe_blocks)] - -
lint-cargo-metadatafor published crates#![warn(clippy::cargo)] - - Run
lint-rustfmt-checkin CIcargo fmt --check - - Configure lints at workspace level
lint-workspace-lints
- - 添加
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-selectiveclippy::pedantic - - 添加
lint-missing-docs#![warn(missing_docs)] - - 添加
lint-unsafe-doc#![warn(clippy::undocumented_unsafe_blocks)] - - 发布的crate添加
lint-cargo-metadata#![warn(clippy::cargo)] - - CI中运行
lint-rustfmt-checkcargo fmt --check - - 在工作区级别配置代码检查规则
lint-workspace-lints
14. Anti-patterns (REFERENCE)
14. 反模式(参考)
- - Don't use
anti-unwrap-abusein production code.unwrap() - - Don't use
anti-expect-lazyfor recoverable errors.expect() - - Don't clone when borrowing works
anti-clone-excessive - - Don't hold locks across
anti-lock-across-await.await - - Don't accept
anti-string-for-strwhen&Stringworks&str - - Don't accept
anti-vec-for-slicewhen&Vec<T>works&[T] - - Don't use indexing when iterators work
anti-index-over-iter - - Don't panic on expected/recoverable errors
anti-panic-expected - - Don't use empty
anti-empty-catchblocksif let Err(_) = ... - - Don't over-abstract with excessive generics
anti-over-abstraction - - Don't optimize before profiling
anti-premature-optimize - - Don't use
anti-type-erasurewhenBox<dyn Trait>worksimpl Trait - - Don't use
anti-format-hot-pathin hot pathsformat!() - - Don't
anti-collect-intermediateintermediate iteratorscollect() - - Don't use strings for structured data
anti-stringly-typed
- - 生产代码中不要使用
anti-unwrap-abuse.unwrap() - - 可恢复错误不要使用
anti-expect-lazy.expect() - - 能借用时不要克隆
anti-clone-excessive - - 不要在
anti-lock-across-await期间持有锁.await - - 能用
anti-string-for-str时不要接收&str&String - - 能用
anti-vec-for-slice时不要接收&[T]&Vec<T> - - 能用迭代器时不要使用索引
anti-index-over-iter - - 预期可恢复的错误不要panic
anti-panic-expected - - 不要使用空的
anti-empty-catch块if let Err(_) = ... - - 不要过度抽象,避免泛型滥用
anti-over-abstraction - - 不要在性能分析前过早优化
anti-premature-optimize - - 能用
anti-type-erasure时不要使用impl TraitBox<dyn Trait> - - 热点路径中不要使用
anti-format-hot-pathformat!() - - 不要对中间迭代器调用
anti-collect-intermediatecollect() - - 结构化数据不要使用字符串
anti-stringly-typed
Recommended Cargo.toml Settings
推荐的Cargo.toml设置
toml
[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 devtoml
[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 devHow 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 examples
rules/
本技能提供规则标识符供快速参考。生成或评审Rust代码时:
- 根据任务类型选择相关分类
- 应用对应前缀的规则
- 按优先级排序:严重 > 高 > 中 > 低
- 阅读目录下的规则文件获取详细示例
rules/
Rule Application by Task
按任务划分的规则应用
| Task | Primary Categories |
|---|---|
| New function | |
| New struct/API | |
| Async code | |
| Error handling | |
| Memory optimization | |
| Performance tuning | |
| Code review | |
| 任务 | 核心分类 |
|---|---|
| 编写新函数 | |
| 编写新结构体/API | |
| 异步代码 | |
| 错误处理 | |
| 内存优化 | |
| 性能调优 | |
| 代码评审 | |
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)
本技能综合了以下来源的最佳实践:
- Rust API 指南
- Rust 性能手册
- Rust 设计模式
- 生产级代码库:ripgrep、tokio、serde、polars、axum、deno
- Clippy 检查规则文档
- 社区约定(2024-2025)