mcpField
R
rust-style-clippy

rust-style-clippy

github.com/full-stack-skills开发12137 次安装5 周前更新
代码仓库

关于 rust-style-clippy

面向需要统一格式、Clippy 检查策略、版本迁移指导和编译器错误说明的 Rust 开发者。内容涵盖配置与 CI 实践,并区分机械化 lint 检查和更广泛的 API 设计工作。

主要功能

  1. 01配置稳定版 rustfmt 格式
  2. 02使用并配置全部 Clippy lint 组
  3. 03设置 lint 策略与优先级
  4. 04迁移 Rust Edition
  5. 05解读常见编译器错误
  6. 06关联 API 指南与 Clippy lint

适用场景

  1. 01格式化 Rust 代码并在 CI 中检查
  2. 02为项目类型选择 lint 设置
  3. 03规划 Rust Edition 迁移
  4. 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.yaml
examples/
examples.md
examples/golden-style/
Cargo.toml
examples/golden-style/src/
lib.rs
references/
api-guidelines-to-clippy.md
clippy-lint-policy.md
production-rust-idioms.md
references.md

详细介绍

Rust 风格格式化与静态分析

基于 rustfmt Book、Clippy Book、Edition Guide 和 Error Code Index。

能力边界

✅ 优势
  1. 稳定版 rustfmt 配置(edition、max_width、tab_spaces、use_field_init_shorthand 等)
  2. Clippy lint 系统 — 全部 10 个 lint 组:correctness、suspicious、style、complexity、perf、pedantic、restriction、cargo、nursery、internal
  3. clippy.toml 配置(msrv、arithmetic-side、cognitive-complexity-threshold、avoid-breaking-exported-api 等)
  4. #[expect(...)] 属性(Rust 1.81+),用于由 CI 强制执行 lint 预期
  5. 用于分层策略的 lint priority 排序
  6. 生产环境 CI lint 策略(针对各组决定 deny/warn/allow)
  7. Edition 迁移(2015→2018→2021→2024,各 Edition 的关键变更和 cargo fix 命令)
  8. 编译器错误代码解读(rustc --explain、常见错误代码参考表)
⚠️ 前提条件
  1. 已安装并配置 Rust 工具链
❌ 不在范围内
  1. Rust 语法基础 → 使用 rust-stable skill
  2. 代码审查 → 使用 rust-code-review skill
  3. API 形态设计(命名、类型/trait 设计、模块布局)以及完整的约 100 条 C-* API 指南检查清单 → 使用 rust-api-design skill。此 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
correctnessdeny(实际上)错误的代码 — 语义有误almost_swap、drop_non_drop、if_same_then_else、out_of_bounds_looping、ptr_offset_with_cast
suspiciouswarn能编译但看起来有问题、可能存在 bug 的代码mutable_key_type、assign_op_pattern、blqcklisted_name、cast_lossless、clone_on_ref_ptr
stylewarn(默认组)符合 Rust 惯用风格的偏好enum_variant_names、new_without_default、wrong_self_convention、needless_return、module_inception
complexitywarn可以写得更简单的代码too_many_arguments、cognitive-complexity、manual_flatten、option_option
perfwarn性能提示(分配、复制)large_enum_variant、single_char_pattern、manual_memcpy、vec_box、derivable_impls
pedanticallow(选择启用)主观的风格要求 — 比 style 更严格cast_possible_truncation、fn_params_excessive_bools、must_use_candidate、missing_errors_doc、module_name_repetitions
restrictionallow(选择启用)禁止可能是有意为之但存在风险的模式unwrap_used、expect_used、panic、indexing_slicing、dbg_macro、print_stdout、float_arithmetic
cargowarnCargo.toml 质量cargo_common_metadata、negative_feature_names、redundant_feature_names、wildcard_dependencies
nurseryallow(实验性)开发中的 lintuse_self、fallible_impl_from、missing_const_for_fn
internalallow用于 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,其中提供了可直接粘贴的配置。

项目类型PedanticRestriction建议
库(已发布)warnallowclippy::all + clippy::pedantic warn + cargo::cargo_common_metadata deny
应用程序 / 二进制文件warnwarn (unwrap_used)添加 restriction::unwrap_used、panic、indexing_slicing
嵌入式 / 安全关键型warndeny所有 restriction lint 均设为 deny;添加 float_arithmetic deny
内部工具allowallow仅使用 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→2024RPIT 生命周期捕获、match ergonomics 调整、临时值作用域、unsafe extern/unsafe 属性、gen 关键字等

IV. 编译器错误代码速查

# View error details
rustc --explain E0277
错误代码含义典型场景
E0277未实现 traitT: 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-UNWRAPclippy::unwrap_usedrestriction标记 unwrap() 调用
C-UNWRAPclippy::expect_usedrestriction标记 expect() 调用
C-PANICclippy::panicrestriction标记 panic!()
C-INDEXINGclippy::indexing_slicingrestriction标记 [i] 索引(会 panic)
C-BOOL-ARGclippy::fn_params_excessive_boolspedantic布尔参数数量 ≥3 的函数
C-NEWTYPEclippy::new_without_defaultstyle存在 new(),但没有 Default
C-NEWTYPEclippy::new_ret_no_selfstylenew() 返回的不是 Self
C-CONV / C-WRONG-SELFclippy::wrong_self_conventionstyleas_X(self) 使用 &self,或 to_X(&self) 消耗 self
C-STRING-PATTERNSclippy::single_char_patternperf.contains("a") → .contains('a')
C-COMMON-TRAITSclippy::derivable_implsperf可通过派生实现的手动 impl
C-LARGE-NUMERICclippy::unreadable_literalstyle1000000 应写为 1_000_000
C-MUTABLE-KEYclippy::mutable_key_typesuspiciousHashMap 的键类型可变
C-CLONE-ON-REFclippy::clone_on_ref_ptrrestriction对 Rc/Arc 使用 .clone()

许多 restriction 和 pedantic lint 默认关闭——在 CI 中强制执行某项指南时,可通过 #![warn(clippy::unwrap_used)] 显式启用,或在 clippy.toml 中配置。

工作流

  1. 格式化代码 — cargo fmt 可确保风格一致
  2. 运行 Clippy — cargo clippy 会运行 5 个默认分组(correctness、suspicious、style、complexity、perf);添加 -W clippy::pedantic 可启用更严格的检查
  3. 确定策略 — 根据项目类型选择 pedantic/restriction 级别(参见上表);粘贴 references/clippy-lint-policy.md 中对应的配置
  4. 配置 clippy.toml — 设置 msrv、disallowed-methods 和任何项目特定阈值
  5. 使用 #[expect] 抑制有意忽略的 lint — 让 CI 能发现不再生效的预期抑制
  6. 检查 Edition — 确认 Cargo.toml 中的 edition 是最新版本
  7. 集成到 CI — 在 CI 中运行 cargo fmt --check + cargo clippy -- -D warnings + cargo audit

注意事项

  1. cargo clippy --fix 只会修复 MachineApplicable 级别的 lint
  2. rustfmt 配置文件名为 .rustfmt.toml,而不是 rustfmt.toml
  3. 迁移 Edition 后可能会出现新的警告——尤其是 2024 中与 unsafe_op_in_unsafe_fn 相关的警告
  4. cargo fix --edition 无法修复所有问题;迁移后需要手动审查
  5. 对于提前退出,优先使用 let ... else;对于简单的布尔映射,使用 is_some_and/then_some;不要为了使用现代语法而压缩复杂的控制流
  6. 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 检查的示例

官方参考资料

评论

支持 Markdown