rust-skills

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rust 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

按优先级划分的规则分类

PriorityCategoryImpactPrefixRules
1Ownership & BorrowingCRITICAL
own-
12
2Error HandlingCRITICAL
err-
12
3Memory OptimizationCRITICAL
mem-
15
4API DesignHIGH
api-
15
5Async/AwaitHIGH
async-
15
6Compiler OptimizationHIGH
opt-
12
7Naming ConventionsMEDIUM
name-
16
8Type SafetyMEDIUM
type-
10
9TestingMEDIUM
test-
13
10DocumentationMEDIUM
doc-
11
11Performance PatternsMEDIUM
perf-
11
12Project StructureLOW
proj-
11
13Clippy & LintingLOW
lint-
11
14Anti-patternsREFERENCE
anti-
15

优先级分类影响等级前缀规则数量
1所有权与借用严重
own-
12
2错误处理严重
err-
12
3内存优化严重
mem-
15
4API设计
api-
15
5Async/Await
async-
15
6编译器优化
opt-
12
7命名规范
name-
16
8类型安全
type-
10
9测试
test-
13
10文档
doc-
11
11性能模式
perf-
11
12项目结构
proj-
11
13Clippy与代码检查
lint-
11
14反模式参考
anti-
15

Quick Reference

快速参考

1. Ownership & Borrowing (CRITICAL)

1. 所有权与借用(严重)

  • own-borrow-over-clone
    - Prefer
    &T
    borrowing over
    .clone()
  • own-slice-over-vec
    - Accept
    &[T]
    not
    &Vec<T>
    ,
    &str
    not
    &String
  • own-cow-conditional
    - Use
    Cow<'a, T>
    for conditional ownership
  • own-arc-shared
    - Use
    Arc<T>
    for thread-safe shared ownership
  • own-rc-single-thread
    - Use
    Rc<T>
    for single-threaded sharing
  • own-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 writes
  • own-copy-small
    - Derive
    Copy
    for small, trivial types
  • own-clone-explicit
    - Make
    Clone
    explicit, avoid implicit copies
  • own-move-large
    - Move large data instead of cloning
  • own-lifetime-elision
    - Rely on lifetime elision when possible
  • own-borrow-over-clone
    - 优先使用
    &T
    借用而非
    .clone()
  • own-slice-over-vec
    - 接收
    &[T]
    而非
    &Vec<T>
    ,接收
    &str
    而非
    &String
  • own-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
    - 为小型、简单类型派生
    Copy
    trait
  • own-clone-explicit
    - 显式使用
    Clone
    ,避免隐式复制
  • own-move-large
    - 移动大型数据而非克隆
  • own-lifetime-elision
    - 尽可能依赖生命周期省略规则

2. Error Handling (CRITICAL)

2. 错误处理(严重)

  • err-thiserror-lib
    - Use
    thiserror
    for library error types
  • err-anyhow-app
    - Use
    anyhow
    for application error handling
  • err-result-over-panic
    - Return
    Result
    , don't panic on expected errors
  • err-context-chain
    - Add context with
    .context()
    or
    .with_context()
  • err-no-unwrap-prod
    - Never use
    .unwrap()
    in production code
  • err-expect-bugs-only
    - Use
    .expect()
    only for programming errors
  • err-question-mark
    - Use
    ?
    operator for clean propagation
  • err-from-impl
    - Use
    #[from]
    for automatic error conversion
  • err-source-chain
    - Use
    #[source]
    to chain underlying errors
  • err-lowercase-msg
    - Error messages: lowercase, no trailing punctuation
  • err-doc-errors
    - Document errors with
    # Errors
    section
  • err-custom-type
    - Create custom error types, not
    Box<dyn Error>
  • err-thiserror-lib
    - 为库的错误类型使用
    thiserror
  • err-anyhow-app
    - 为应用的错误处理使用
    anyhow
  • err-result-over-panic
    - 返回
    Result
    ,对预期错误不要panic
  • 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-type
    - 创建自定义错误类型,而非使用
    Box<dyn Error>

3. Memory Optimization (CRITICAL)

3. 内存优化(严重)

  • mem-with-capacity
    - Use
    with_capacity()
    when size is known
  • mem-smallvec
    - Use
    SmallVec
    for usually-small collections
  • mem-arrayvec
    - Use
    ArrayVec
    for bounded-size collections
  • mem-box-large-variant
    - Box large enum variants to reduce type size
  • mem-boxed-slice
    - Use
    Box<[T]>
    instead of
    Vec<T>
    when fixed
  • mem-thinvec
    - Use
    ThinVec
    for often-empty vectors
  • mem-clone-from
    - Use
    clone_from()
    to reuse allocations
  • mem-reuse-collections
    - Reuse collections with
    clear()
    in loops
  • mem-avoid-format
    - Avoid
    format!()
    when string literals work
  • mem-write-over-format
    - Use
    write!()
    instead of
    format!()
  • mem-arena-allocator
    - Use arena allocators for batch allocations
  • mem-zero-copy
    - Use zero-copy patterns with slices and
    Bytes
  • mem-compact-string
    - Use
    CompactString
    for small string optimization
  • mem-smaller-integers
    - Use smallest integer type that fits
  • mem-assert-type-size
    - Assert hot type sizes to prevent regressions
  • mem-with-capacity
    - 已知容量时使用
    with_capacity()
  • mem-smallvec
    - 对通常较小的集合使用
    SmallVec
  • mem-arrayvec
    - 对有界大小的集合使用
    ArrayVec
  • mem-box-large-variant
    - 对大型枚举变体使用Box包裹以减少类型大小
  • mem-boxed-slice
    - 固定大小场景下使用
    Box<[T]>
    而非
    Vec<T>
  • mem-thinvec
    - 对经常为空的向量使用
    ThinVec
  • mem-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
    - 对小型字符串使用
    CompactString
    优化
  • mem-smaller-integers
    - 使用能容纳数据的最小整数类型
  • mem-assert-type-size
    - 断言热点类型的大小以防止性能退化

4. API Design (HIGH)

4. API设计(高)

  • api-builder-pattern
    - Use Builder pattern for complex construction
  • api-builder-must-use
    - Add
    #[must_use]
    to builder types
  • api-newtype-safety
    - Use newtypes for type-safe distinctions
  • api-typestate
    - Use typestate for compile-time state machines
  • api-sealed-trait
    - Seal traits to prevent external implementations
  • api-extension-trait
    - Use extension traits to add methods to foreign types
  • api-parse-dont-validate
    - Parse into validated types at boundaries
  • api-impl-into
    - Accept
    impl Into<T>
    for flexible string inputs
  • api-impl-asref
    - Accept
    impl AsRef<T>
    for borrowed inputs
  • api-must-use
    - Add
    #[must_use]
    to
    Result
    returning functions
  • api-non-exhaustive
    - Use
    #[non_exhaustive]
    for future-proof enums/structs
  • api-from-not-into
    - Implement
    From
    , not
    Into
    (auto-derived)
  • api-default-impl
    - Implement
    Default
    for sensible defaults
  • api-common-traits
    - Implement
    Debug
    ,
    Clone
    ,
    PartialEq
    eagerly
  • api-serde-optional
    - Gate
    Serialize
    /
    Deserialize
    behind feature flag
  • api-builder-pattern
    - 复杂构造场景使用构建器模式
  • api-builder-must-use
    - 为构建器类型添加
    #[must_use]
    属性
  • api-newtype-safety
    - 使用新类型实现类型安全的区分
  • api-typestate
    - 使用类型状态实现编译时状态机
  • api-sealed-trait
    - 密封trait以防止外部实现
  • api-extension-trait
    - 使用扩展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-impl
    - 为合理的默认值实现
    Default
    trait
  • api-common-traits
    - 尽早实现
    Debug
    Clone
    PartialEq
    等通用trait
  • api-serde-optional
    - 将
    Serialize
    /
    Deserialize
    放在feature flag后

5. Async/Await (HIGH)

5. Async/Await(高)

  • async-tokio-runtime
    - Use Tokio for production async runtime
  • async-no-lock-await
    - Never hold
    Mutex
    /
    RwLock
    across
    .await
  • async-spawn-blocking
    - Use
    spawn_blocking
    for CPU-intensive work
  • async-tokio-fs
    - Use
    tokio::fs
    not
    std::fs
    in async code
  • async-cancellation-token
    - Use
    CancellationToken
    for graceful shutdown
  • async-join-parallel
    - Use
    tokio::join!
    for parallel operations
  • async-try-join
    - Use
    tokio::try_join!
    for fallible parallel ops
  • async-select-racing
    - Use
    tokio::select!
    for racing/timeouts
  • async-bounded-channel
    - Use bounded channels for backpressure
  • async-mpsc-queue
    - Use
    mpsc
    for work queues
  • async-broadcast-pubsub
    - Use
    broadcast
    for pub/sub patterns
  • async-watch-latest
    - Use
    watch
    for latest-value sharing
  • async-oneshot-response
    - Use
    oneshot
    for request/response
  • async-joinset-structured
    - Use
    JoinSet
    for dynamic task groups
  • async-clone-before-await
    - Clone data before await, release locks
  • async-tokio-runtime
    - 生产环境异步代码使用Tokio运行时
  • async-no-lock-await
    - 绝不要在
    .await
    期间持有
    Mutex
    /
    RwLock
  • async-spawn-blocking
    - CPU密集型任务使用
    spawn_blocking
  • async-tokio-fs
    - 异步代码中使用
    tokio::fs
    而非
    std::fs
  • async-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
    - 工作队列场景使用
    mpsc
  • async-broadcast-pubsub
    - 发布/订阅模式使用
    broadcast
  • async-watch-latest
    - 最新值共享场景使用
    watch
  • async-oneshot-response
    - 请求/响应场景使用
    oneshot
  • async-joinset-structured
    - 动态任务组使用
    JoinSet
  • async-clone-before-await
    - 在await前克隆数据,释放锁

6. Compiler Optimization (HIGH)

6. 编译器优化(高)

  • opt-inline-small
    - Use
    #[inline]
    for small hot functions
  • opt-inline-always-rare
    - Use
    #[inline(always)]
    sparingly
  • opt-inline-never-cold
    - Use
    #[inline(never)]
    for cold paths
  • opt-cold-unlikely
    - Use
    #[cold]
    for error/unlikely paths
  • opt-likely-hint
    - Use
    likely()
    /
    unlikely()
    for branch hints
  • opt-lto-release
    - Enable LTO in release builds
  • opt-codegen-units
    - Use
    codegen-units = 1
    for max optimization
  • opt-pgo-profile
    - Use PGO for production builds
  • opt-target-cpu
    - Set
    target-cpu=native
    for local builds
  • opt-bounds-check
    - Use iterators to avoid bounds checks
  • opt-simd-portable
    - Use portable SIMD for data-parallel ops
  • opt-cache-friendly
    - Design cache-friendly data layouts (SoA)
  • 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
    - 发布构建中启用LTO
  • opt-codegen-units
    - 使用
    codegen-units = 1
    以获得最大优化效果
  • opt-pgo-profile
    - 生产构建使用PGO(性能引导优化)
  • opt-target-cpu
    - 本地构建设置
    target-cpu=native
  • opt-bounds-check
    - 使用迭代器避免边界检查
  • opt-simd-portable
    - 数据并行操作使用可移植SIMD
  • opt-cache-friendly
    - 设计缓存友好的数据布局(SoA)

7. Naming Conventions (MEDIUM)

7. 命名规范(中)

  • name-types-camel
    - Use
    UpperCamelCase
    for types, traits, enums
  • name-variants-camel
    - Use
    UpperCamelCase
    for enum variants
  • name-funcs-snake
    - Use
    snake_case
    for functions, methods, modules
  • name-consts-screaming
    - Use
    SCREAMING_SNAKE_CASE
    for constants/statics
  • name-lifetime-short
    - Use short lowercase lifetimes:
    'a
    ,
    'de
    ,
    'src
  • name-type-param-single
    - Use single uppercase for type params:
    T
    ,
    E
    ,
    K
    ,
    V
  • name-as-free
    -
    as_
    prefix: free reference conversion
  • name-to-expensive
    -
    to_
    prefix: expensive conversion
  • name-into-ownership
    -
    into_
    prefix: ownership transfer
  • name-no-get-prefix
    - No
    get_
    prefix for simple getters
  • name-is-has-bool
    - Use
    is_
    ,
    has_
    ,
    can_
    for boolean methods
  • name-iter-convention
    - Use
    iter
    /
    iter_mut
    /
    into_iter
    for iterators
  • name-iter-method
    - Name iterator methods consistently
  • name-iter-type-match
    - Iterator type names match method
  • name-acronym-word
    - Treat acronyms as words:
    Uuid
    not
    UUID
  • name-crate-no-rs
    - Crate names: no
    -rs
    suffix
  • name-types-camel
    - 类型、trait、枚举使用
    UpperCamelCase
  • name-variants-camel
    - 枚举变体使用
    UpperCamelCase
  • name-funcs-snake
    - 函数、方法、模块使用
    snake_case
  • name-consts-screaming
    - 常量/静态变量使用
    SCREAMING_SNAKE_CASE
  • name-lifetime-short
    - 使用短小写字母作为生命周期名称:
    'a
    'de
    'src
  • name-type-param-single
    - 使用单个大写字母作为类型参数:
    T
    E
    K
    V
  • name-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_iter
    命名
  • name-iter-method
    - 迭代器方法命名保持一致
  • name-iter-type-match
    - 迭代器类型名称与方法名匹配
  • name-acronym-word
    - 首字母缩写词视为单词:
    Uuid
    而非
    UUID
  • name-crate-no-rs
    - crate名称不要使用
    -rs
    后缀

8. Type Safety (MEDIUM)

8. 类型安全(中)

  • type-newtype-ids
    - Wrap IDs in newtypes:
    UserId(u64)
  • type-newtype-validated
    - Newtypes for validated data:
    Email
    ,
    Url
  • type-enum-states
    - Use enums for mutually exclusive states
  • type-option-nullable
    - Use
    Option<T>
    for nullable values
  • type-result-fallible
    - Use
    Result<T, E>
    for fallible operations
  • type-phantom-marker
    - Use
    PhantomData<T>
    for type-level markers
  • type-never-diverge
    - Use
    !
    type for functions that never return
  • type-generic-bounds
    - Add trait bounds only where needed
  • type-no-stringly
    - Avoid stringly-typed APIs, use enums/newtypes
  • type-repr-transparent
    - Use
    #[repr(transparent)]
    for FFI newtypes
  • type-newtype-ids
    - 使用新类型包裹ID:
    UserId(u64)
  • type-newtype-validated
    - 使用新类型包裹已验证数据:
    Email
    Url
  • type-enum-states
    - 互斥状态使用枚举
  • type-option-nullable
    - 可空值使用
    Option<T>
  • type-result-fallible
    - 可能失败的操作使用
    Result<T, E>
  • type-phantom-marker
    - 类型级别标记使用
    PhantomData<T>
  • type-never-diverge
    - 永不返回的函数使用
    !
    类型
  • type-generic-bounds
    - 仅在需要时添加trait约束
  • type-no-stringly
    - 避免字符串化API,使用枚举/新类型
  • type-repr-transparent
    - FFI场景的新类型使用
    #[repr(transparent)]

9. Testing (MEDIUM)

9. 测试(中)

  • test-cfg-test-module
    - Use
    #[cfg(test)] mod tests { }
  • test-use-super
    - Use
    use super::*;
    in test modules
  • test-integration-dir
    - Put integration tests in
    tests/
    directory
  • test-descriptive-names
    - Use descriptive test names
  • test-arrange-act-assert
    - Structure tests as arrange/act/assert
  • test-proptest-properties
    - Use
    proptest
    for property-based testing
  • test-mockall-mocking
    - Use
    mockall
    for trait mocking
  • test-mock-traits
    - Use traits for dependencies to enable mocking
  • test-fixture-raii
    - Use RAII pattern (Drop) for test cleanup
  • test-tokio-async
    - Use
    #[tokio::test]
    for async tests
  • test-should-panic
    - Use
    #[should_panic]
    for panic tests
  • test-criterion-bench
    - Use
    criterion
    for benchmarking
  • test-doctest-examples
    - Keep doc examples as executable tests
  • test-cfg-test-module
    - 使用
    #[cfg(test)] mod tests { }
    定义测试模块
  • test-use-super
    - 测试模块中使用
    use super::*;
  • test-integration-dir
    - 集成测试放在
    tests/
    目录下
  • test-descriptive-names
    - 使用描述性的测试名称
  • test-arrange-act-assert
    - 测试结构遵循“准备/执行/断言”模式
  • test-proptest-properties
    - 属性测试使用
    proptest
  • test-mockall-mocking
    - trait mocking使用
    mockall
  • test-mock-traits
    - 依赖项使用trait以支持mock
  • test-fixture-raii
    - 测试清理使用RAII模式(Drop trait)
  • test-tokio-async
    - 异步测试使用
    #[tokio::test]
  • test-should-panic
    - panic测试使用
    #[should_panic]
  • test-criterion-bench
    - 基准测试使用
    criterion
  • test-doctest-examples
    - 文档示例保持可执行性

10. Documentation (MEDIUM)

10. 文档(中)

  • doc-all-public
    - Document all public items with
    ///
  • doc-module-inner
    - Use
    //!
    for module-level documentation
  • doc-examples-section
    - Include
    # Examples
    with runnable code
  • doc-errors-section
    - Include
    # Errors
    for fallible functions
  • doc-panics-section
    - Include
    # Panics
    for panicking functions
  • doc-safety-section
    - Include
    # Safety
    for unsafe functions
  • doc-question-mark
    - Use
    ?
    in examples, not
    .unwrap()
  • doc-hidden-setup
    - Use
    # 
    prefix to hide example setup code
  • doc-intra-links
    - Use intra-doc links:
    [Vec]
  • doc-link-types
    - Link related types and functions in docs
  • doc-cargo-metadata
    - Fill
    Cargo.toml
    metadata
  • doc-all-public
    - 使用
    ///
    为所有公共项编写文档
  • doc-module-inner
    - 使用
    //!
    编写模块级文档
  • doc-examples-section
    - 包含
    # Examples
    章节并提供可运行代码
  • doc-errors-section
    - 为可能失败的函数添加
    # Errors
    章节
  • doc-panics-section
    - 为可能panic的函数添加
    # 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. 性能模式(中)

  • perf-iter-over-index
    - Prefer iterators over manual indexing
  • perf-iter-lazy
    - Keep iterators lazy, collect() only when needed
  • perf-collect-once
    - Don't
    collect()
    intermediate iterators
  • perf-entry-api
    - Use
    entry()
    API for map insert-or-update
  • perf-drain-reuse
    - Use
    drain()
    to reuse allocations
  • perf-extend-batch
    - Use
    extend()
    for batch insertions
  • perf-chain-avoid
    - Avoid
    chain()
    in hot loops
  • perf-collect-into
    - Use
    collect_into()
    for reusing containers
  • perf-black-box-bench
    - Use
    black_box()
    in benchmarks
  • perf-release-profile
    - Optimize release profile settings
  • perf-profile-first
    - Profile before optimizing
  • perf-iter-over-index
    - 优先使用迭代器而非手动索引
  • perf-iter-lazy
    - 保持迭代器惰性,仅在需要时使用
    collect()
  • perf-collect-once
    - 不要对中间迭代器调用
    collect()
  • perf-entry-api
    - 映射的插入或更新使用
    entry()
    API
  • perf-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
    - 优化前先进行性能分析

12. Project Structure (LOW)

12. 项目结构(低)

  • proj-lib-main-split
    - Keep
    main.rs
    minimal, logic in
    lib.rs
  • proj-mod-by-feature
    - Organize modules by feature, not type
  • proj-flat-small
    - Keep small projects flat
  • proj-mod-rs-dir
    - Use
    mod.rs
    for multi-file modules
  • proj-pub-crate-internal
    - Use
    pub(crate)
    for internal APIs
  • proj-pub-super-parent
    - Use
    pub(super)
    for parent-only visibility
  • proj-pub-use-reexport
    - Use
    pub use
    for clean public API
  • proj-prelude-module
    - Create
    prelude
    module for common imports
  • proj-bin-dir
    - Put multiple binaries in
    src/bin/
  • proj-workspace-large
    - Use workspaces for large projects
  • proj-workspace-deps
    - Use workspace dependency inheritance
  • proj-lib-main-split
    - 保持
    main.rs
    简洁,业务逻辑放在
    lib.rs
  • proj-mod-by-feature
    - 按功能而非类型组织模块
  • proj-flat-small
    - 小型项目保持扁平化结构
  • proj-mod-rs-dir
    - 多文件模块使用
    mod.rs
  • proj-pub-crate-internal
    - 内部API使用
    pub(crate)
  • proj-pub-super-parent
    - 仅对父模块可见的API使用
    pub(super)
  • proj-pub-use-reexport
    - 使用
    pub use
    构建清晰的公共API
  • 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)]
  • lint-pedantic-selective
    - Enable
    clippy::pedantic
    selectively
  • lint-missing-docs
    -
    #![warn(missing_docs)]
  • lint-unsafe-doc
    -
    #![warn(clippy::undocumented_unsafe_blocks)]
  • lint-cargo-metadata
    -
    #![warn(clippy::cargo)]
    for published crates
  • lint-rustfmt-check
    - Run
    cargo fmt --check
    in CI
  • lint-workspace-lints
    - Configure lints at workspace level
  • 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
    - 选择性启用
    clippy::pedantic
  • lint-missing-docs
    - 添加
    #![warn(missing_docs)]
  • lint-unsafe-doc
    - 添加
    #![warn(clippy::undocumented_unsafe_blocks)]
  • lint-cargo-metadata
    - 发布的crate添加
    #![warn(clippy::cargo)]
  • lint-rustfmt-check
    - CI中运行
    cargo fmt --check
  • lint-workspace-lints
    - 在工作区级别配置代码检查规则

14. Anti-patterns (REFERENCE)

14. 反模式(参考)

  • anti-unwrap-abuse
    - Don't use
    .unwrap()
    in production code
  • anti-expect-lazy
    - Don't use
    .expect()
    for recoverable errors
  • anti-clone-excessive
    - Don't clone when borrowing works
  • anti-lock-across-await
    - Don't hold locks across
    .await
  • anti-string-for-str
    - Don't accept
    &String
    when
    &str
    works
  • anti-vec-for-slice
    - Don't accept
    &Vec<T>
    when
    &[T]
    works
  • anti-index-over-iter
    - Don't use indexing when iterators work
  • anti-panic-expected
    - Don't panic on expected/recoverable errors
  • anti-empty-catch
    - Don't use empty
    if let Err(_) = ...
    blocks
  • anti-over-abstraction
    - Don't over-abstract with excessive generics
  • anti-premature-optimize
    - Don't optimize before profiling
  • anti-type-erasure
    - Don't use
    Box<dyn Trait>
    when
    impl Trait
    works
  • anti-format-hot-path
    - Don't use
    format!()
    in hot paths
  • anti-collect-intermediate
    - Don't
    collect()
    intermediate iterators
  • anti-stringly-typed
    - Don't use strings for structured data

  • 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
    - 能用迭代器时不要使用索引
  • anti-panic-expected
    - 预期可恢复的错误不要panic
  • anti-empty-catch
    - 不要使用空的
    if let Err(_) = ...
  • anti-over-abstraction
    - 不要过度抽象,避免泛型滥用
  • anti-premature-optimize
    - 不要在性能分析前过早优化
  • anti-type-erasure
    - 能用
    impl Trait
    时不要使用
    Box<dyn Trait>
  • anti-format-hot-path
    - 热点路径中不要使用
    format!()
  • anti-collect-intermediate
    - 不要对中间迭代器调用
    collect()
  • 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 dev

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 dev

How to Use

使用方法

This skill provides rule identifiers for quick reference. When generating or reviewing Rust code:
  1. Check relevant category based on task type
  2. Apply rules with matching prefix
  3. Prioritize CRITICAL > HIGH > MEDIUM > LOW
  4. Read rule files in
    rules/
    for detailed examples
本技能提供规则标识符供快速参考。生成或评审Rust代码时:
  1. 根据任务类型选择相关分类
  2. 应用对应前缀的规则
  3. 按优先级排序:严重 > 高 > 中 > 低
  4. 阅读
    rules/
    目录下的规则文件
    获取详细示例

Rule Application by Task

按任务划分的规则应用

TaskPrimary 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-

任务核心分类
编写新函数
own-
,
err-
,
name-
编写新结构体/API
api-
,
type-
,
doc-
异步代码
async-
,
own-
错误处理
err-
,
api-
内存优化
mem-
,
own-
,
perf-
性能调优
opt-
,
mem-
,
perf-
代码评审
anti-
,
lint-

Sources

参考来源

This skill synthesizes best practices from:
本技能综合了以下来源的最佳实践: