rust-idioms
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRust Community Rust Refactoring Best Practices
Rust社区Rust重构最佳实践
Comprehensive refactoring and idiomatic patterns guide for Rust applications, maintained by the Rust Community. Contains 44 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
由Rust社区维护的Rust应用程序全面重构与惯用模式指南。包含8个类别共44条规则,按影响优先级排序,可指导自动化重构与代码生成。
When to Apply
适用场景
Reference these guidelines when:
- Writing new Rust code with strong type guarantees
- Refactoring ownership and borrowing patterns
- Designing error handling strategies
- Creating public APIs with traits and generics
- Organizing modules and controlling visibility
在以下场景中可参考本指南:
- 编写具备强类型保证的新Rust代码
- 重构所有权与借用模式
- 设计错误处理策略
- 基于trait与泛型创建公共API
- 组织模块并控制可见性
Rule Categories by Priority
按优先级划分的规则类别
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Type Safety & Newtype Patterns | CRITICAL | |
| 2 | Ownership & Borrowing | CRITICAL | |
| 3 | Error Handling Patterns | HIGH | |
| 4 | API Design & Traits | HIGH | |
| 5 | Module & Visibility | MEDIUM-HIGH | |
| 6 | Conversion Traits | MEDIUM | |
| 7 | Idiomatic Patterns | MEDIUM | |
| 8 | Iterator & Collections | LOW-MEDIUM | |
| 优先级 | 类别 | 影响等级 | 前缀 |
|---|---|---|---|
| 1 | 类型安全与Newtype模式 | 关键 | |
| 2 | 所有权与借用 | 关键 | |
| 3 | 错误处理模式 | 高 | |
| 4 | API设计与Trait | 高 | |
| 5 | 模块与可见性 | 中高 | |
| 6 | 转换Trait | 中 | |
| 7 | 惯用模式 | 中 | |
| 8 | 迭代器与集合 | 中低 | |
Quick Reference
快速参考
1. Type Safety & Newtype Patterns (CRITICAL)
1. 类型安全与Newtype模式(关键)
- - Use newtype pattern for unit safety
type-newtype-units - - Encode invariants in newtype constructors
type-newtype-invariants - - Use non-exhaustive for extensible enums
type-non-exhaustive-enums - - Use PhantomData for type-level state
type-phantom-data - - Replace stringly-typed APIs with strong types
type-strong-typing-strings - - Use typestate builders for required fields
type-builder-required-fields
- - 使用Newtype模式保证单元安全
type-newtype-units - - 在Newtype构造函数中编码不变量
type-newtype-invariants - - 对可扩展枚举使用non-exhaustive
type-non-exhaustive-enums - - 使用PhantomData实现类型级状态
type-phantom-data - - 用强类型替换字符串类型的API
type-strong-typing-strings - - 使用类型状态构建器处理必填字段
type-builder-required-fields
2. Ownership & Borrowing (CRITICAL)
2. 所有权与借用(关键)
- - Prefer borrowing over ownership in parameters
own-prefer-borrowing - - Use Cow for conditional ownership
own-cow-conditional-clone - - Accept borrowed types over owned references
own-accept-borrowed-types - - Return owned types for caller flexibility
own-return-owned-for-flexibility - - Avoid unnecessary clone calls
own-avoid-unnecessary-clone - - Leverage lifetime elision rules
own-lifetime-elision
- - 参数优先使用借用而非所有权
own-prefer-borrowing - - 使用Cow实现条件式所有权
own-cow-conditional-clone - - 接受借用类型而非自有引用
own-accept-borrowed-types - - 返回自有类型以提升调用方灵活性
own-return-owned-for-flexibility - - 避免不必要的clone调用
own-avoid-unnecessary-clone - - 利用生命周期省略规则
own-lifetime-elision
3. Error Handling Patterns (HIGH)
3. 错误处理模式(高)
- - Use Result instead of panic! for recoverable errors
err-use-result-not-panic - - Use thiserror for library error types
err-thiserror-for-libraries - - Use anyhow for application error handling
err-anyhow-for-applications - - Use the question mark operator for error propagation
err-question-mark-propagation - - Use Option for absence, not sentinel values
err-option-for-absence
- - 可恢复错误使用Result而非panic!
err-use-result-not-panic - - 库错误类型使用thiserror
err-thiserror-for-libraries - - 应用程序错误处理使用anyhow
err-anyhow-for-applications - - 使用问号操作符传播错误
err-question-mark-propagation - - 使用Option表示值不存在,而非标记值
err-option-for-absence
4. API Design & Traits (HIGH)
4. API设计与Trait(高)
- - Derive common traits for public types
api-derive-common-traits - - Implement standard traits for ergonomic APIs
api-impl-standard-traits - - Use trait bounds for generic flexibility
api-generic-bounds - - Use sealed traits to prevent external implementation
api-sealed-traits - - Use builder pattern for complex construction
api-builder-pattern - - Use extension traits to add methods to foreign types
api-extension-traits
- - 为公共类型派生常用trait
api-derive-common-traits - - 实现标准trait以打造易用API
api-impl-standard-traits - - 使用trait边界提升泛型灵活性
api-generic-bounds - - 使用密封trait防止外部实现
api-sealed-traits - - 使用构建器模式处理复杂构造逻辑
api-builder-pattern - - 使用扩展trait为外部类型添加方法
api-extension-traits
5. Module & Visibility (MEDIUM-HIGH)
5. 模块与可见性(中高)
- - Minimize public API surface
mod-minimize-pub-api - - Use pub use for clean module re-exports
mod-pub-use-reexports - - Split large modules into submodules
mod-split-large-modules - - Use crate:: prefix for internal imports
mod-crate-prefix-imports - - Use tests submodule for unit tests
mod-tests-submodule
- - 最小化公共API表面
mod-minimize-pub-api - - 使用pub use实现清晰的模块重导出
mod-pub-use-reexports - - 将大型模块拆分为子模块
mod-split-large-modules - - 内部导入使用crate::前缀
mod-crate-prefix-imports - - 使用tests子模块存放单元测试
mod-tests-submodule
6. Conversion Traits (MEDIUM)
6. 转换Trait(中)
- - Implement From instead of Into
conv-impl-from-not-into - - Accept AsRef for flexible string parameters
conv-asref-for-flexibility - - Implement Deref for transparent newtype access
conv-impl-deref-for-newtypes - - Use TryFrom for fallible conversions
conv-tryfrom-for-fallible - - Use inner function pattern to reduce monomorphization
conv-inner-function-pattern
- - 实现From而非Into
conv-impl-from-not-into - - 接受AsRef以提升字符串参数灵活性
conv-asref-for-flexibility - - 为透明Newtype实现Deref以方便访问
conv-impl-deref-for-newtypes - - 使用TryFrom处理可失败的转换
conv-tryfrom-for-fallible - - 使用内部函数模式减少单态化
conv-inner-function-pattern
7. Idiomatic Patterns (MEDIUM)
7. 惯用模式(中)
- - Implement Default instead of new() without arguments
idiom-default-trait - - Follow constructor naming conventions
idiom-constructor-naming - - Use let-else for early returns on pattern match failure
idiom-let-else - - Use struct update syntax for partial overrides
idiom-struct-update-syntax - - Use destructuring for multiple returns and field access
idiom-destructuring-assignment - - Use match guards for complex conditions
idiom-match-guards
- - 实现Default而非无参new()
idiom-default-trait - - 遵循构造函数命名规范
idiom-constructor-naming - - 使用let-else在模式匹配失败时提前返回
idiom-let-else - - 使用结构体更新语法进行部分覆盖
idiom-struct-update-syntax - - 使用解构处理多返回值与字段访问
idiom-destructuring-assignment - - 使用match guard处理复杂条件
idiom-match-guards
8. Iterator & Collections (LOW-MEDIUM)
8. 迭代器与集合(中低)
- - Prefer iterator methods over manual loops
iter-prefer-iterators-over-loops - - Use turbofish for explicit collect type
iter-use-collect-turbofish - - Use filter_map for combined filter and transform
iter-filter-map-combined - - Avoid collecting then iterating
iter-avoid-collect-then-iterate - - Use enumerate instead of manual index tracking
iter-enumerate-for-indices
- - 优先使用迭代器方法而非手动循环
iter-prefer-iterators-over-loops - - 使用turbofish指定collect的明确类型
iter-use-collect-turbofish - - 使用filter-map组合过滤与转换操作
iter-filter-map-combined - - 避免先收集再迭代的操作
iter-avoid-collect-then-iterate - - 使用enumerate而非手动跟踪索引
iter-enumerate-for-indices
How to Use
使用方法
Read individual reference files for detailed explanations and code examples:
- Section definitions - Category structure and impact levels
- Rule template - Template for adding new rules
阅读单个参考文件获取详细说明与代码示例:
- 章节定义 - 类别结构与影响等级说明
- 规则模板 - 添加新规则的模板
Full Compiled Document
完整编译文档
For a single-file comprehensive guide, see AGENTS.md.
如需单文件版的全面指南,请查看AGENTS.md。