rust-style-clippy
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRust Style Formatting and Static Analysis
Rust 风格、格式化与静态分析
Capability Boundaries
能力边界
✅ Strengths
✅ 优势
- Stable rustfmt configuration (edition, max_width, tab_spaces, use_field_init_shorthand, etc.)
- Clippy lint system — all 10 lint groups: correctness, suspicious, style, complexity, perf, pedantic, restriction, cargo, nursery, internal
- configuration (msrv, arithmetic-side, cognitive-complexity-threshold, avoid-breaking-exported-api, etc.)
clippy.toml - attribute (Rust 1.81+) for CI-enforced lint expectations
#[expect(...)] - Lint ordering for layered policy
priority - Production CI lint policy (deny/warn/allow decisions per group)
- Edition migration (2015→2018→2021→2024, key changes per edition and cargo fix commands)
- Compiler error code interpretation (rustc --explain, common error codes reference table)
- 稳定的 rustfmt 配置(edition、max_width、tab_spaces、use_field_init_shorthand 等)
- Clippy lint 系统——全部 10 个 lint 组:correctness、suspicious、style、complexity、perf、pedantic、restriction、cargo、nursery、internal
- 配置(msrv、arithmetic-side、cognitive-complexity-threshold、avoid-breaking-exported-api 等)
clippy.toml - 属性(Rust 1.81+),用于 CI 强制执行的 lint 预期
#[expect(...)] - Lint 排序,用于分层策略
priority - 生产环境 CI lint 策略(按组决定 deny/warn/allow)
- Edition 迁移(2015→2018→2021→2024、各 Edition 的关键变化以及 cargo fix 命令)
- 编译器错误代码解读(rustc --explain、常见错误代码速查表)
⚠️ Prerequisites
⚠️ 前置条件
- Rust toolchain installed and configured
- 已安装并配置 Rust 工具链
❌ Out of Scope
❌ 不在范围内
- Rust syntax basics → Use skill
rust-stable - Code review → Use skill
rust-code-review - API shape design (naming, type/trait design, module layout) and the full ~100 C-* API Guidelines checklist → Use the skill. This skill only maps the ~25 C-* rules that Clippy can mechanically enforce; the rest are design decisions.
rust-api-design
- Rust 语法基础 → 使用 skill
rust-stable - 代码审查 → 使用 skill
rust-code-review - API 形状设计(命名、类型/trait 设计、模块布局)以及完整的约 100 条 C-* API Guidelines 检查清单 → 使用 skill。此 skill 仅映射 Clippy 能够机械检查的约 25 条 C-* 规则,其余规则属于设计决策。
rust-api-design
When to Use
使用时机
- "Format Rust code"
- "Run Clippy"
- "Migrate to a new Edition"
- "What does compiler error E0xxx mean?"
- “格式化 Rust 代码”
- “运行 Clippy”
- “迁移到新 Edition”
- “编译器错误 E0xxx 表示什么?”
I. rustfmt Configuration
I. rustfmt 配置
toml
undefinedtoml
undefined.rustfmt.toml
.rustfmt.toml
max_width = 100 # Line width (default: 100)
tab_spaces = 4 # Indentation spaces
edition = "2024" # Rust edition
merge_derives = true # Merge derives
use_field_init_shorthand = true # Field initialization shorthand
use_try_shorthand = true # Use ? shorthand
```bash
cargo fmt # Format all files
cargo fmt --check # Check formatting (CI usage)
cargo fmt -- --config max_width=80 # Apply specific configurationOptions such as , , and may still require nightly rustfmt; do not include them in default configurations that must pass stable CI.
imports_granularitygroup_importsreorder_impl_itemsmax_width = 100 # Line width (default: 100)
tab_spaces = 4 # Indentation spaces
edition = "2024" # Rust edition
merge_derives = true # Merge derives
use_field_init_shorthand = true # Field initialization shorthand
use_try_shorthand = true # Use ? shorthand
```bash
cargo fmt # Format all files
cargo fmt --check # Check formatting (CI usage)
cargo fmt -- --config max_width=80 # Apply specific configurationimports_granularitygroup_importsreorder_impl_itemsII. Clippy
II. Clippy
bash
cargo clippy # Default: correctness, suspicious, style, complexity, perf
cargo clippy -- -W clippy::pedantic # Enable pedantic group
cargo clippy --fix # Auto-fix MachineApplicable lints
cargo clippy -- -A clippy::module_inception # Allow a specific lintbash
cargo clippy # Default: correctness, suspicious, style, complexity, perf
cargo clippy -- -W clippy::pedantic # Enable pedantic group
cargo clippy --fix # Auto-fix MachineApplicable lints
cargo clippy -- -A clippy::module_inception # Allow a specific lintAll 10 lint groups
全部 10 个 lint 组
| Group | Default level | Description | High-leverage lints |
|---|---|---|---|
| deny (effectively) | Code that is wrong — broken semantics | |
| warn | Likely-buggy code that compiles but smells off | |
| warn (default group) | Idiomatic Rust stylistic preferences | |
| warn | Code that could be simpler | |
| warn | Performance hints (allocations, copies) | |
| allow (opt-in) | Opinionated style — stricter than style | |
| allow (opt-in) | Forbid patterns that may be intentional but risky | |
| warn | | |
| allow (experimental) | Lints under development | |
| allow | For Clippy's own development | (rarely used by users) |
| 组 | 默认级别 | 说明 | 高收益 lint |
|---|---|---|---|
| deny(实际上) | 错误的代码——语义已损坏 | |
| warn | 可以编译但可能存在问题的可疑代码 | |
| warn(默认组) | 符合 Rust 惯用法的风格偏好 | |
| warn | 可以简化的代码 | |
| warn | 性能提示(内存分配、复制操作) | |
| allow(需主动启用) | 主观性较强的风格——比 style 更严格 | |
| allow(需主动启用) | 禁止可能有意使用但具有风险的模式 | |
| warn | | |
| allow(实验性) | 开发中的 lint | |
| allow | 供 Clippy 自身开发使用 | 用户很少使用 |
#[expect]
attribute (Rust 1.81+) — better than #[allow]
#[expect]#[allow]#[expect]
属性(Rust 1.81+)——优于 #[allow]
#[expect]#[allow]rust
// ✅ #[expect] — CI fails if the lint stops firing, surfacing dead expectations
#[expect(clippy::too_many_arguments, reason = "configurable builder has many options")]
fn build(name: &str, retries: u32, timeout: u32, /* 5 more */) { /* */ }
// ❌ #[allow] — silently becomes dead code if the lint stops firing
#[allow(clippy::too_many_arguments)]
fn build(/* */) { /* */ }Prefer for intentional suppressions; reserve for transient reasons.
#[expect]#[allow]rust
// ✅ #[expect] — CI fails if the lint stops firing, surfacing dead expectations
#[expect(clippy::too_many_arguments, reason = "configurable builder has many options")]
fn build(name: &str, retries: u32, timeout: u32, /* 5 more */) { /* */ }
// ❌ #[allow] — silently becomes dead code if the lint stops firing
#[allow(clippy::too_many_arguments)]
fn build(/* */) { /* */ }对于有意进行的 lint 抑制,应优先使用 ;仅在临时原因下使用 。
#[expect]#[allow]Lint priority
— layering
priorityLint priority
——分层配置
priorityrust
// Higher priority wins. Use for layered policy.
#![warn(clippy::pedantic)] // enable pedantic (priority 0)
#![warn(priority = 1, clippy::module_name_repetitions)] // re-enable a specific lintrust
// Higher priority wins. Use for layered policy.
#![warn(clippy::pedantic)] # enable pedantic (priority 0)
#![warn(priority = 1, clippy::module_name_repetitions)] # re-enable a specific lintclippy.toml
configuration
clippy.tomlclippy.toml
配置
clippy.tomltoml
undefinedtoml
undefinedclippy.toml at workspace root
clippy.toml at workspace root
msrv = "1.85" # Don't suggest APIs newer than MSRV
avoid-breaking-exported-api = false # Suggest fixes that change public API
cognitive-complexity-threshold = 25 # Function complexity limit
arithmetic-side = "checked" # Prefer checked_* arithmetic
enum-variant-name-threshold = 1 # Trigger variant_name lint
single-char-binding-names-threshold = 3 # Allow , , but not 4+
too-many-arguments-threshold = 7
type-complexity-threshold = 250
disallowed-methods = [
{ path = "std::env::var", reason = "use our config::get instead" },
]
disallowed-types = [
{ path = "std::collections::LinkedList", reason = "almost never the right choice" },
]
disallowed-macros = [
{ path = "std::println", reason = "use tracing in libraries" },
]
_a_b
See `references/clippy-lint-policy.md` for the full `clippy.toml` reference and production policies.msrv = "1.85" # Don't suggest APIs newer than MSRV
avoid-breaking-exported-api = false # Suggest fixes that change public API
cognitive-complexity-threshold = 25 # Function complexity limit
arithmetic-side = "checked" # Prefer checked_* arithmetic
enum-variant-name-threshold = 1 # Trigger variant_name lint
single-char-binding-names-threshold = 3 # Allow , , but not 4+
too-many-arguments-threshold = 7
type-complexity-threshold = 250
disallowed-methods = [
{ path = "std::env::var", reason = "use our config::get instead" },
]
disallowed-types = [
{ path = "std::collections::LinkedList", reason = "almost never the right choice" },
]
disallowed-macros = [
{ path = "std::println", reason = "use tracing in libraries" },
]
_a_b
有关完整的 `clippy.toml` 参考和生产环境策略,请参阅 `references/clippy-lint-policy.md`。Production CI lint policy
生产环境 CI lint 策略
Different projects need different strictness. See for ready-to-paste configurations.
references/clippy-lint-policy.md| Project type | Pedantic | Restriction | Recommended |
|---|---|---|---|
| Library (published) | warn | allow | |
| Application / binary | warn | warn ( | Add |
| Embedded / safety-critical | warn | deny | All restriction lints deny; add |
| Internal tool | allow | allow | Just |
不同项目需要采用不同的严格程度。有关可直接粘贴的配置,请参阅 。
references/clippy-lint-policy.md| 项目类型 | Pedantic | Restriction | 推荐配置 |
|---|---|---|---|
| 库(已发布) | warn | allow | |
| 应用/二进制 | warn | warn( | 添加 |
| 嵌入式/安全关键 | warn | deny | 将所有 restriction lint 设为 deny;添加 |
| 内部工具 | allow | allow | 仅使用 |
III. Edition Migration
III. Edition 迁移
bash
undefinedbash
undefinedCheck current edition
Check current edition
cargo metadata --format-version 1 | jq '.packages[0].edition'
cargo metadata --format-version 1 | jq '.packages[0].edition'
Migration steps (example: 2021 → 2024)
Migration steps (example: 2021 → 2024)
cargo fix --edition # Auto-migrate code
cargo build # Verify compilation
cargo test # Validate functionality
cargo fix --edition # Auto-migrate code
cargo build # Verify compilation
cargo test # Validate functionality
Update Cargo.toml
Update Cargo.toml
edition = "2024"
edition = "2024"
Key changes per edition:
| Edition | Key Changes |
|---------|-------------|
| 2015→2018 | Path and module import changes, `dyn Trait`, NLL, anonymous lifetimes and keywords changed |
| 2018→2021 | Precise closure capture, array `IntoIterator`, panic macro consistency, prelude and reserved syntax changes |
| 2021→2024 | RPIT lifetime capture, match ergonomics adjustment, temporary value scope, `unsafe extern`/unsafe attributes, `gen` keyword, etc. |
各 Edition 的关键变化:
| Edition | 关键变化 |
|---------|-------------|
| 2015→2018 | 路径和模块导入变化、`dyn Trait`、NLL、匿名生命周期以及关键字变更 |
| 2018→2021 | 精确闭包捕获、数组 `IntoIterator`、panic 宏一致性、prelude 和保留语法变更 |
| 2021→2024 | RPIT 生命周期捕获、match ergonomics 调整、临时值作用域、`unsafe extern`/unsafe 属性、`gen` 关键字等 |IV. Compiler Error Code Quick Reference
IV. 编译器错误代码速查
bash
undefinedbash
undefinedView error details
View error details
rustc --explain E0277
| Error Code | Meaning | Typical Scenario |
|------------|---------|------------------|
| E0277 | Trait not implemented | `T: Trait` bound is unsatisfied |
| E0308 | Type mismatch | Expected type A, but B provided |
| E0502 | Borrow conflict | Cannot have mutable borrow and immutable borrow simultaneously |
| E0597 | Insufficient lifetimes | Reference goes out of scope beyond its lifetime value |
| E0432 | Import not found | `use` path is incorrect |
| E0061 | Parameter count mismatch | Function call has wrong number of parameters |
| E0106 | Missing lifetimes | Function signature requires explicit lifetimes |
| E0382 | Use moved value | Ownership already transferred |
| E0499 | Simultaneous mutable borrow | Only one `&mut` allowed per expression |
| E0716 | Insufficient lifetime for temporary values | Reference on temporary exceeds its scope |rustc --explain E0277
| 错误代码 | 含义 | 典型场景 |
|------------|---------|------------------|
| E0277 | 未实现 Trait | `T: Trait` 约束未满足 |
| E0308 | 类型不匹配 | 期望类型 A,但提供了 B |
| E0502 | 借用冲突 | 无法同时拥有可变借用和不可变借用 |
| E0597 | 生命周期不足 | 引用超出其生命周期值所允许的作用范围 |
| E0432 | 找不到导入 | `use` 路径不正确 |
| E0061 | 参数数量不匹配 | 函数调用传入了错误数量的参数 |
| E0106 | 缺少生命周期 | 函数签名要求显式指定生命周期 |
| E0382 | 使用已移动的值 | 所有权已经转移 |
| E0499 | 同时进行可变借用 | 单个表达式中只能有一个 `&mut` |
| E0716 | 临时值生命周期不足 | 对临时值的引用超出了其作用域 |V. API Guidelines ↔ Clippy Lints
V. API Guidelines ↔ Clippy Lints
The Rust API Guidelines checklist uses rules (about 100 total). Clippy mechanically enforces roughly 25 of them; the remaining ~75 are design judgments (naming, type/trait shape, module layout) that belong to the skill, or require for breaking-change detection. The table below lists the 12 highest-leverage mappings reviewers ask about most. The full crosswalk, including "lints not yet covered" guidance, lives in .
C-*rust-api-designcargo-semver-checksreferences/api-guidelines-to-clippy.md| C-* Rule | Clippy Lint | Group | Effect |
|---|---|---|---|
| C-UNWRAP | | restriction | Flags |
| C-UNWRAP | | restriction | Flags |
| C-PANIC | | restriction | Flags |
| C-INDEXING | | restriction | Flags |
| C-BOOL-ARG | | pedantic | Functions with ≥3 bool params |
| C-NEWTYPE | | style | |
| C-NEWTYPE | | style | |
| C-CONV / C-WRONG-SELF | | style | |
| C-STRING-PATTERNS | | perf | |
| C-COMMON-TRAITS | | perf | Manual impl that could be derived |
| C-LARGE-NUMERIC | | style | |
| C-MUTABLE-KEY | | suspicious | |
| C-CLONE-ON-REF | | restriction | |
Many and lints are off by default — enable them explicitly via or in when enforcing a guideline in CI.
restrictionpedantic#![warn(clippy::unwrap_used)]clippy.tomlRust API Guidelines 检查清单使用 规则(共约 100 条)。Clippy 能够机械检查其中约 25 条;其余约 75 条属于设计判断(命名、类型/trait 形状、模块布局),应交由 skill 处理,或使用 检测破坏性变更。下表列出了审查者最常询问的 12 个高收益映射。完整对照表,包括“尚未覆盖的 lint”相关指导,位于 。
C-*rust-api-designcargo-semver-checksreferences/api-guidelines-to-clippy.md| C-* 规则 | Clippy Lint | 组 | 效果 |
|---|---|---|---|
| C-UNWRAP | | restriction | 标记 |
| C-UNWRAP | | restriction | 标记 |
| C-PANIC | | restriction | 标记 |
| C-INDEXING | | restriction | 标记 |
| C-BOOL-ARG | | pedantic | 函数包含 ≥3 个 bool 参数 |
| C-NEWTYPE | | style | 存在 |
| C-NEWTYPE | | style | |
| C-CONV / C-WRONG-SELF | | style | |
| C-STRING-PATTERNS | | perf | |
| C-COMMON-TRAITS | | perf | 手动实现的 trait 可以通过 derive 派生 |
| C-LARGE-NUMERIC | | style | |
| C-MUTABLE-KEY | | suspicious | |
| C-CLONE-ON-REF | | restriction | 对 |
许多 和 lint 默认关闭——应在 CI 中通过 或在 中显式启用,以强制执行对应规范。
restrictionpedantic#![warn(clippy::unwrap_used)]clippy.tomlWorkflow
工作流
- Format code — ensures consistent style
cargo fmt - Run Clippy — runs the 5 default groups (correctness, suspicious, style, complexity, perf); add
cargo clippyfor stricter-W clippy::pedantic - Decide policy — pick pedantic/restriction level by project type (see table above); paste the matching config from
references/clippy-lint-policy.md - Configure — set
clippy.toml,msrv, and any project-specific thresholdsdisallowed-methods - Use for intentional suppressions — keeps CI honest about dead expectations
#[expect] - Check Edition — Confirm edition in Cargo.toml is up-to-date
- CI integration — +
cargo fmt --check+cargo clippy -- -D warningsin CIcargo audit
- 格式化代码——确保代码风格一致
cargo fmt - 运行 Clippy——运行 5 个默认组(correctness、suspicious、style、complexity、perf);如需更严格的检查,添加
cargo clippy-W clippy::pedantic - 决定策略——按项目类型选择 pedantic/restriction 级别(见上表),并粘贴 中对应的配置
references/clippy-lint-policy.md - 配置 ——设置
clippy.toml、msrv和项目特定的阈值disallowed-methods - 对有意进行的抑制使用 ——让 CI 如实暴露已经失效的预期
#[expect] - 检查 Edition——确认 Cargo.toml 中的 edition 已是最新版本
- 集成 CI——在 CI 中运行 +
cargo fmt --check+cargo clippy -- -D warningscargo audit
Gotchas
常见陷阱
- only fixes lints at MachineApplicable level
cargo clippy --fix - rustfmt config file is named , not
.rustfmt.tomlrustfmt.toml - After edition migration, new warnings may appear — especially around unsafe_op_in_unsafe_fn in 2024
- does not fix all issues; manual review required after migration
cargo fix --edition - Prefer for early exits and
let ... else/is_some_andfor simple boolean mapping; avoid compressing complex control flows just to use modern syntaxthen_some - ,
saturating_*, and regular arithmetic expressions have different business semantics regarding overflow strategy — decide first, then select APIchecked_*
- 只能修复 MachineApplicable 级别的 lint
cargo clippy --fix - rustfmt 配置文件名为 ,而不是
.rustfmt.tomlrustfmt.toml - Edition 迁移后可能出现新的警告——尤其是 2024 中与 unsafe_op_in_unsafe_fn 相关的问题
- 无法修复所有问题;迁移后仍需手动审查
cargo fix --edition - 对于提前退出,优先使用 ;对于简单的布尔值映射,使用
let ... else/is_some_and;不要仅仅为了使用现代语法而压缩复杂的控制流then_some - 、
saturating_*和常规算术表达式在溢出策略方面具有不同的业务语义——应先确定策略,再选择 APIchecked_*
On-Demand Resources
按需资源
- Format and Clippy Examples
- Lint Group Quick Reference
- Clippy Lint Policy: Full reference, all 10 lint groups in depth,
clippy.tomlpatterns,#[expect]layering, and ready-to-paste production CI configurations by project type.priority - Production Rust Idioms: Review let-else, Option combinators, newtype patterns, non-exhaustive APIs, lock scopes, and overflow strategies when reviewing production code.
- API Guidelines ↔ Clippy Lints Crosswalk: Full mapping from Rust API Guidelines rules to the Clippy lints that enforce them, plus the ~75 rules Clippy does not cover and where to review them.
C-* - : Golden examples for CI passing rustfmt and Clippy
examples/golden-style/
- 格式化与 Clippy 示例
- Lint 组速查
- Clippy Lint 策略:完整的 参考、全部 10 个 lint 组的深入说明、
clippy.toml模式、#[expect]分层,以及按项目类型提供的可直接粘贴的生产环境 CI 配置。priority - 生产级 Rust 惯用法:审查生产代码中的 let-else、Option combinator、newtype 模式、non-exhaustive API、锁作用域和溢出策略。
- API Guidelines ↔ Clippy Lints 对照表:从 Rust API Guidelines 的 规则到负责强制执行它们的 Clippy lint 的完整映射,同时涵盖 Clippy 尚未覆盖的约 75 条规则及其审查位置。
C-* - :可通过 CI 中 rustfmt 和 Clippy 检查的黄金示例
examples/golden-style/