关于 rust-style-clippy
面向需要统一格式、Clippy 检查策略、版本迁移指导和编译器错误说明的 Rust 开发者。内容涵盖配置与 CI 实践,并区分机械化 lint 检查和更广泛的 API 设计工作。
主要功能
- 01配置稳定版 rustfmt 格式
- 02使用并配置全部 Clippy lint 组
- 03设置 lint 策略与优先级
- 04迁移 Rust Edition
- 05解读常见编译器错误
- 06关联 API 指南与 Clippy lint
适用场景
- 01格式化 Rust 代码并在 CI 中检查
- 02为项目类型选择 lint 设置
- 03规划 Rust Edition 迁移
- 04理解 rustc 错误代码
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ full-stack-skills/ rust-skills --skill rust-style-clippy安装后在 Claude Code 中输入/rust-style-clippy确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
agents/openai.yamlexamples/examples.mdexamples/golden-style/Cargo.tomlexamples/golden-style/src/lib.rsreferences/api-guidelines-to-clippy.mdclippy-lint-policy.mdproduction-rust-idioms.mdreferences.md详细介绍
Rust 风格格式化与静态分析
基于
rustfmt Book、Clippy Book、Edition Guide和Error Code Index。
能力边界
✅ 优势
- 稳定版 rustfmt 配置(edition、max_width、tab_spaces、use_field_init_shorthand 等)
- Clippy lint 系统 — 全部 10 个 lint 组:correctness、suspicious、style、complexity、perf、pedantic、restriction、cargo、nursery、internal
clippy.toml配置(msrv、arithmetic-side、cognitive-complexity-threshold、avoid-breaking-exported-api 等)#[expect(...)]属性(Rust 1.81+),用于由 CI 强制执行 lint 预期- 用于分层策略的 lint
priority排序 - 生产环境 CI lint 策略(针对各组决定 deny/warn/allow)
- Edition 迁移(2015→2018→2021→2024,各 Edition 的关键变更和 cargo fix 命令)
- 编译器错误代码解读(rustc --explain、常见错误代码参考表)
⚠️ 前提条件
- 已安装并配置 Rust 工具链
❌ 不在范围内
- Rust 语法基础 → 使用
rust-stableskill - 代码审查 → 使用
rust-code-reviewskill - API 形态设计(命名、类型/trait 设计、模块布局)以及完整的约 100 条 C-* API 指南检查清单 → 使用
rust-api-designskill。此 skill 仅涵盖 Clippy 可通过机械方式强制执行的约 25 条 C-* 规则;其余属于设计决策。
适用场景
- “格式化 Rust 代码”
- “运行 Clippy”
- “迁移到新的 Edition”
- “编译器错误 E0xxx 是什么意思?”
I. rustfmt 配置
# .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
cargo fmt # Format all files
cargo fmt --check # Check formatting (CI usage)
cargo fmt -- --config max_width=80 # Apply specific configuration
imports_granularity、group_imports 和 reorder_impl_items 等选项可能仍需 nightly rustfmt;对于必须通过稳定版 CI 的默认配置,不要包含这些选项。
II. Clippy
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 lint
全部 10 个 lint 组
| 组 | 默认级别 | 描述 | 影响较大的 lint |
|---|---|---|---|
correctness | deny(实际上) | 错误的代码 — 语义有误 | almost_swap、drop_non_drop、if_same_then_else、out_of_bounds_looping、ptr_offset_with_cast |
suspicious | warn | 能编译但看起来有问题、可能存在 bug 的代码 | mutable_key_type、assign_op_pattern、blqcklisted_name、cast_lossless、clone_on_ref_ptr |
style | warn(默认组) | 符合 Rust 惯用风格的偏好 | enum_variant_names、new_without_default、wrong_self_convention、needless_return、module_inception |
complexity | warn | 可以写得更简单的代码 | too_many_arguments、cognitive-complexity、manual_flatten、option_option |
perf | warn | 性能提示(分配、复制) | large_enum_variant、single_char_pattern、manual_memcpy、vec_box、derivable_impls |
pedantic | allow(选择启用) | 主观的风格要求 — 比 style 更严格 | cast_possible_truncation、fn_params_excessive_bools、must_use_candidate、missing_errors_doc、module_name_repetitions |
restriction | allow(选择启用) | 禁止可能是有意为之但存在风险的模式 | unwrap_used、expect_used、panic、indexing_slicing、dbg_macro、print_stdout、float_arithmetic |
cargo | warn | Cargo.toml 质量 | cargo_common_metadata、negative_feature_names、redundant_feature_names、wildcard_dependencies |
nursery | allow(实验性) | 开发中的 lint | use_self、fallible_impl_from、missing_const_for_fn |
internal | allow | 用于 Clippy 自身的开发 | (用户很少使用) |
#[expect] 属性(Rust 1.81+)——优于 #[allow]
// ✅ #[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(/* */) { /* */ }
对于有意进行的抑制,优先使用 #[expect];#[allow] 仅用于临时原因。
lint priority — 分层
// 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 lint
clippy.toml 配置
# 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 `_a`, `_b`, 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" },
]
完整的 clippy.toml 参考和生产环境策略请参阅 references/clippy-lint-policy.md。
生产环境 CI lint 策略
不同项目需要不同的严格程度。可查看 references/clippy-lint-policy.md,其中提供了可直接粘贴的配置。
| 项目类型 | Pedantic | Restriction | 建议 |
|---|---|---|---|
| 库(已发布) | warn | allow | clippy::all + clippy::pedantic warn + cargo::cargo_common_metadata deny |
| 应用程序 / 二进制文件 | warn | warn (unwrap_used) | 添加 restriction::unwrap_used、panic、indexing_slicing |
| 嵌入式 / 安全关键型 | warn | deny | 所有 restriction lint 均设为 deny;添加 float_arithmetic deny |
| 内部工具 | allow | allow | 仅使用 clippy::all(默认组) |
III. Edition 迁移
# Check current edition
cargo metadata --format-version 1 | jq '.packages[0].edition'
# Migration steps (example: 2021 → 2024)
cargo fix --edition # Auto-migrate code
cargo build # Verify compilation
cargo test # Validate functionality
# Update Cargo.toml
# edition = "2024"
各 Edition 的主要变更:
| Edition | 主要变更 |
|---|---|
| 2015→2018 | 路径和模块导入变更、dyn Trait、NLL、匿名生命周期和关键字变更 |
| 2018→2021 | 闭包精确捕获、数组 IntoIterator、panic 宏一致性、prelude 和保留语法变更 |
| 2021→2024 | RPIT 生命周期捕获、match ergonomics 调整、临时值作用域、unsafe extern/unsafe 属性、gen 关键字等 |
IV. 编译器错误代码速查
# View error details
rustc --explain E0277
| 错误代码 | 含义 | 典型场景 |
|---|---|---|
| E0277 | 未实现 trait | T: Trait 约束未满足 |
| E0308 | 类型不匹配 | 预期类型 A,但提供了 B |
| E0502 | 借用冲突 | 不能同时存在可变借用和不可变借用 |
| E0597 | 生命周期不足 | 引用超出其生命周期值的作用域 |
| E0432 | 未找到导入项 | use 路径不正确 |
| E0061 | 参数数量不匹配 | 函数调用的参数数量错误 |
| E0106 | 缺少生命周期 | 函数签名需要显式生命周期 |
| E0382 | 使用已移动的值 | 所有权已转移 |
| E0499 | 同时进行可变借用 | 每个表达式中只允许一个 &mut |
| E0716 | 临时值的生命周期不足 | 对临时值的引用超出其作用域 |
V. API 指南 ↔ Clippy Lint
Rust API 指南检查清单使用 C-* 规则(总计约 100 条)。Clippy 以机械方式强制执行其中约 25 条;其余约 75 条属于设计判断(命名、类型/trait 形态、模块布局),应由 rust-api-design 技能处理,或使用 cargo-semver-checks 检测破坏性变更。下表列出了审查者最常询问、影响最大的 12 条对应关系。完整的对照表(包括“尚未覆盖的 lint”指南)位于 references/api-guidelines-to-clippy.md。
| C-* 规则 | Clippy Lint | 分组 | 效果 |
|---|---|---|---|
| C-UNWRAP | clippy::unwrap_used | restriction | 标记 unwrap() 调用 |
| C-UNWRAP | clippy::expect_used | restriction | 标记 expect() 调用 |
| C-PANIC | clippy::panic | restriction | 标记 panic!() |
| C-INDEXING | clippy::indexing_slicing | restriction | 标记 [i] 索引(会 panic) |
| C-BOOL-ARG | clippy::fn_params_excessive_bools | pedantic | 布尔参数数量 ≥3 的函数 |
| C-NEWTYPE | clippy::new_without_default | style | 存在 new(),但没有 Default |
| C-NEWTYPE | clippy::new_ret_no_self | style | new() 返回的不是 Self |
| C-CONV / C-WRONG-SELF | clippy::wrong_self_convention | style | as_X(self) 使用 &self,或 to_X(&self) 消耗 self |
| C-STRING-PATTERNS | clippy::single_char_pattern | perf | .contains("a") → .contains('a') |
| C-COMMON-TRAITS | clippy::derivable_impls | perf | 可通过派生实现的手动 impl |
| C-LARGE-NUMERIC | clippy::unreadable_literal | style | 1000000 应写为 1_000_000 |
| C-MUTABLE-KEY | clippy::mutable_key_type | suspicious | HashMap 的键类型可变 |
| C-CLONE-ON-REF | clippy::clone_on_ref_ptr | restriction | 对 Rc/Arc 使用 .clone() |
许多 restriction 和 pedantic lint 默认关闭——在 CI 中强制执行某项指南时,可通过 #![warn(clippy::unwrap_used)] 显式启用,或在 clippy.toml 中配置。
工作流
- 格式化代码 —
cargo fmt可确保风格一致 - 运行 Clippy —
cargo clippy会运行 5 个默认分组(correctness、suspicious、style、complexity、perf);添加-W clippy::pedantic可启用更严格的检查 - 确定策略 — 根据项目类型选择 pedantic/restriction 级别(参见上表);粘贴
references/clippy-lint-policy.md中对应的配置 - 配置
clippy.toml— 设置msrv、disallowed-methods和任何项目特定阈值 - 使用
#[expect]抑制有意忽略的 lint — 让 CI 能发现不再生效的预期抑制 - 检查 Edition — 确认 Cargo.toml 中的 edition 是最新版本
- 集成到 CI — 在 CI 中运行
cargo fmt --check+cargo clippy -- -D warnings+cargo audit
注意事项
cargo clippy --fix只会修复 MachineApplicable 级别的 lint- rustfmt 配置文件名为
.rustfmt.toml,而不是rustfmt.toml - 迁移 Edition 后可能会出现新的警告——尤其是 2024 中与 unsafe_op_in_unsafe_fn 相关的警告
cargo fix --edition无法修复所有问题;迁移后需要手动审查- 对于提前退出,优先使用
let ... else;对于简单的布尔映射,使用is_some_and/then_some;不要为了使用现代语法而压缩复杂的控制流 saturating_*、checked_*和常规算术表达式在溢出策略方面具有不同的业务语义——先确定策略,再选择 API
按需资源
- 格式和 Clippy 示例
- Lint 组速查表
- Clippy Lint 策略:完整的
clippy.toml参考,深入介绍全部 10 个 lint 组、#[expect]用法、priority分层,以及按项目类型整理、可直接粘贴使用的生产环境 CI 配置。 - 生产环境 Rust 惯用写法:审查生产代码时,检查 let-else、Option 组合器、新类型模式、非穷尽 API、锁作用域和溢出处理策略。
- API 指南 ↔ Clippy Lint 对照表:将 Rust API 指南中的
C-*规则完整映射到用于强制执行这些规则的 Clippy lint,并列出 Clippy 未覆盖的大约 75 条规则及其审查方式。 examples/golden-style/:通过 rustfmt 和 Clippy CI 检查的示例