Clippy

← 返回目录 > ← 返回总览

相关工具推荐

工具 说明
Rustfmt Rust 官方代码格式化工具,与 Clippy 互补
ShellCheck Shell 脚本静态分析工具,适合与 Clippy 配合检查混合项目
Pre-commit 多语言 Git 钩子管理框架,Clippy 的主流集成方式之一

1. 简介

Clippy 是 Rust 官方提供的代码检查(lint)工具,由 Rust 项目团队维护,作为 Rust 工具链的核心组件随 Rust 编译器一同分发。Clippy 内置超过 800 条检查规则(lint),旨在帮助开发者捕获常见错误、优化性能、推广 Rust 惯用法(idiomatic Rust),并统一代码风格。

Clippy 基于 Rust 编译器的高层中间表示(HIR)进行语义级别的静态分析,能够理解类型推导、生命周期和泛型等编译器特性,因此其检查精度远超基于文本匹配的 lint 工具。

  • 主要检查语言:Rust
  • 主要检查能力:检测 Rust 代码中的常见错误、性能瓶颈、代码异味、惯用法违规;涵盖质量类检查(correctness、suspicious)、风格类检查(style)、复杂度检查(complexity)、性能检查(perf)
  • 核心检查原理:基于 rustc 编译器 HIR(高级中间表示)语义分析
  • 检查规则/选项:822 条 lint(按 Correctness、Suspicious、Style、Complexity、Perf、Pedantic、Restriction、Nursery、Cargo 等 9 个 lint group 组织),全量 lint 列表
  • GitHub 仓库https://github.com/rust-lang/rust-clippy(13,267 stars,截至 2026-06-12)
  • 开源协议:MIT / Apache-2.0
  • 最新稳定版本:随 Rust 工具链发布(无独立版本号,通过 rustup 管理)
  • 运行环境要求:需 Rust 工具链(rustup + Cargo),随 Rust 版本发布
  • 误报率:低

2. 官方文档

资源 链接
Clippy 官方文档(Book) https://doc.rust-lang.org/clippy/
安装指南 https://doc.rust-lang.org/clippy/installation.html
使用指南 https://doc.rust-lang.org/clippy/usage.html
配置指南(含告警抑制) https://doc.rust-lang.org/clippy/configuration.html
Lint 配置项参考 https://doc.rust-lang.org/clippy/lint_configuration.html
所有 Lint 规则列表 https://rust-lang.github.io/rust-clippy/master/index.html
Lint 分组说明 https://doc.rust-lang.org/clippy/lints.html
GitHub Actions 集成 https://doc.rust-lang.org/clippy/continuous_integration/github_actions.html
GitLab CI 集成 https://doc.rust-lang.org/clippy/continuous_integration/gitlab.html
Travis CI 集成 https://doc.rust-lang.org/clippy/continuous_integration/travis.html
Cargo 的 [lints] Section 文档 https://doc.rust-lang.org/nightly/cargo/reference/manifest.html#the-lints-section
Rustc Lint Levels 文档 https://doc.rust-lang.org/rustc/lints/levels.html

3. 社区优秀实践

3.1 Tokio

Tokio 是 Rust 生态中最主流的异步运行时框架,在 CI 流水线中设置独立的 Clippy 检查 job,并设置全局 RUSTFLAGS: -Dwarnings 将所有警告(包括 Clippy lints)视为错误,确保所有合入代码均通过严格的质量门禁。

  • 仓库https://github.com/tokio-rs/tokio
  • CI 配置:在 GitHub Actions 中配置独立的 clippy job,使用 dtolnay/rust-toolchain@stable 并指定 Clippy 版本(如 rust_clippy: '1.88'),作为 basics job 的前置依赖
  • 特点:Workspace 级别统一配置,Clippy 检查是 CI 基础门禁的一部分,所有后续测试 job 依赖 Clippy 通过后才执行

3.2 Serde

Serde 是 Rust 生态中最广泛使用的序列化/反序列化框架,几乎所有 Rust 项目都直接或间接依赖它。Serde 在 CI 中配置独立的 Clippy job,对每个子 crate 分别运行 Clippy 检查,同时启用 clippy::allclippy::pedantic 组。

  • 仓库https://github.com/serde-rs/serde
  • CI 配置:使用 dtolnay/rust-toolchain@clippy 安装 Clippy 专用工具链,对 serdeserde_coreserde_deriveserde_derive_internalstest_suite 等子 crate 分别运行 cargo clippy -- -Dclippy::all -Dclippy::pedantic
  • 特点:多 crate Workspace 架构,逐 crate 精细化 Clippy 检查,启用 pedantic 组实现更严格的代码质量标准

3.3 Clap

Clap 是 Rust 生态中最流行的命令行参数解析库,在项目根目录维护了 .clippy.toml 配置文件进行精细化规则管理,在 CI 中配置独立的 Clippy job 对多种 feature 组合进行检查。

  • 仓库https://github.com/clap-rs/clap
  • 配置文件.clippy.toml,配置了测试环境下的宽松策略(allow-print-in-testsallow-expect-in-testsallow-unwrap-in-testsallow-dbg-in-tests),以及禁止使用的方法列表(如 Option::map_orIterator::for_each 等)
  • CI 配置:在 GitHub Actions 中配置独立的 clippy job,使用 dtolnay/rust-toolchain@stable 并安装 clippy 组件,分别对 minimal、full、release 等 feature 组合运行 Clippy 检查
  • 特点:Workspace 架构(包含 clap_builder、clap_derive、clap_complete 等子 crate),通过 Makefile 封装 Clippy 命令,结合 .clippy.toml 实现精细化规则管理

3.4 Rust 编译器自身(rust-lang/rust)

Rust 编译器仓库(rust-lang/rust)本身就将 Clippy 作为子项目维护(src/tools/clippy),Clippy 的每次变更都需要通过编译器仓库的 CI 验证。Clippy 自身也使用 Clippy 进行自身检查(启用 clippy::pedantic 组),并维护了 .clippy.toml 配置文件。

  • 仓库https://github.com/rust-lang/rust
  • 实践方式:Clippy 作为 rust-lang/rust 的子目录存在,每次提交都经过完整的 Clippy 检查;Clippy 自身的 .clippy.toml 配置了 avoid-breaking-exported-api = falselint-commented-code = true 等规则,以及禁止使用的方法列表
  • 特点:Clippy 项目自身就是 Clippy 最佳实践的示范

4. 工具配置说明

4.1 配置文件说明

Clippy 支持通过两种方式进行项目级配置:

配置文件 用途 使用场景
clippy.toml / .clippy.toml Lint 行为参数配置(阈值、允许列表等) 需要调整 lint 行为参数的项目
Cargo.toml [lints] Lint 级别配置(allow/warn/deny/forbid) 所有 Rust 项目,控制 lint 规则的启用和级别

注意clippy.toml 用于调整 lint 行为参数(如阈值、允许列表等),不能用于 allow/deny lint。allow/deny 需通过代码属性、命令行参数或 Cargo.toml[lints] 段配置。

clippy.toml 配置文件查找优先级

  1. 环境变量 CLIPPY_CONF_DIR 指定的目录
  2. 环境变量 CARGO_MANIFEST_DIR 指定的目录(即 Cargo.toml 所在目录)
  3. 当前工作目录

如果指定目录下未找到配置文件,Clippy 会向上逐级搜索父目录,直到找到配置文件或到达文件系统根目录。

4.2 clippy.toml 配置详解

配置项说明

配置项 类型 说明
msrv string 项目支持的最低 Rust 版本(MSRV)
avoid-breaking-exported-api bool 是否因检查而破坏已导出的 API(内部项目设为 false,库项目建议保持 true)
check-inconsistent-struct-field-initializers bool 是否检查不一致的结构体字段初始化顺序
disallowed-names string[] 禁止使用的变量名列表
disallowed-methods object[] 禁止使用的特定方法列表,每项含 pathreason
disallowed-types object[] 禁止使用的特定类型列表,每项含 pathreason
allow-unwrap-in-tests bool 在测试中允许使用 unwrap()
allow-expect-in-tests bool 在测试中允许使用 expect()
allow-dbg-in-tests bool 在测试中允许使用 dbg!

最小配置示例

# clippy.toml

# 项目支持的最低 Rust 版本(MSRV)
msrv = "1.70.0"

完整配置示例

# clippy.toml

# 不因检查而破坏已导出的 API(适合内部项目设为 false,库项目建议保持 true)
avoid-breaking-exported-api = false

# 项目支持的最低 Rust 版本(MSRV)
msrv = "1.70.0"

# 检查不一致的结构体字段初始化顺序
check-inconsistent-struct-field-initializers = true

# 禁止使用的变量名
disallowed-names = ["foo", "baz", "quux"]

# 禁止使用的特定方法
[[disallowed-methods]]
path = "std::iter::Iterator::for_each"
reason = "请使用 for 循环处理副作用"

# 禁止使用的类型
[[disallowed-types]]
path = "std::collections::HashMap"
reason = "请使用 IndexMap 替代以保持插入顺序"

推荐配置示例(适用于需要更精细控制 lint 行为参数的场景):

# clippy.toml

# 不因检查而破坏已导出的 API(适合内部项目设为 false,库项目建议保持 true)
avoid-breaking-exported-api = false

# 项目支持的最低 Rust 版本
msrv = "1.70.0"

# 检查不一致的结构体字段初始化顺序
check-inconsistent-struct-field-initializers = true

# 在测试中放宽限制
allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-dbg-in-tests = true

# 禁止使用的特定方法
[[disallowed-methods]]
path = "std::process::exit"
reason = "请使用优雅关闭机制替代直接退出进程"

配置文件参考:配置指南 | Lint 配置项完整列表

4.3 Cargo.toml [lints] 推荐配置

通过 Cargo.toml[lints] 段配置 lint 级别(allow/warn/deny/forbid),支持单 crate 和 Workspace 两种模式。

方案一:标准项目(适用于大多数 Rust 项目)

在默认规则基础上启用 pedantic 组,并选择性屏蔽部分过于严格的规则:

# Cargo.toml

[lints.clippy]
# 启用所有默认规则(correctness + suspicious + style + complexity + perf)
all = "warn"

# 启用 pedantic 组(更严格的代码质量检查)
pedantic = "warn"

# 以下 pedantic 组中的规则在特定场景下可能过于严格,按需 allow
# missing_errors_doc = "allow"       # 不要求所有 fallible 函数都有错误文档
# missing_panics_doc = "allow"       # 不要求所有可能 panic 的函数都有文档
# must_use_candidate = "allow"       # 不强制标注所有应使用的返回值
# module_name_repetitions = "allow"  # 允许模块名与项名重复

# 从 restriction 组中精选有价值的规则
unwrap_used = "warn"                  # 警告使用 unwrap()(可能导致 panic)
expect_used = "warn"                 # 警告使用 expect()(可能导致 panic)
panic = "warn"                       # 警告显式 panic
todo = "warn"                        # 警告 TODO 标记

方案二:严格项目(适用于库/框架等对代码质量有极高要求的项目)

启用更多 restriction 组规则:

# Cargo.toml

[lints.clippy]
# 所有默认规则设为 deny
all = "deny"

# 启用 pedantic 组
pedantic = "warn"

# 精选 restriction 组规则
unwrap_used = "deny"                 # 禁止使用 unwrap()
expect_used = "deny"                 # 禁止使用 expect()
panic = "deny"                       # 禁止显式 panic
todo = "deny"                        # 禁止 TODO 标记
float_arithmetic = "warn"            # 警告浮点运算(适用于精确计算场景)
indexing_slicing = "warn"            # 警告直接索引/切片操作(建议使用 get 方法)

方案三:Workspace 统一配置(适用于多 crate 项目)

在根目录统一配置,子 crate 继承:

Workspace 根 Cargo.toml

# Cargo.toml(Workspace 根)

[workspace.lints.clippy]
all = "warn"
pedantic = "warn"
unwrap_used = "warn"
expect_used = "warn"
panic = "deny"
todo = "warn"
unnecessary_wraps = "warn"
redundant_clone = "warn"

[workspace.lints.rust]
unsafe_code = "forbid"               # 禁止 unsafe 代码(可选)

[workspace.lints]
workspace = true

子 crate 的 Cargo.toml

# crates/my-crate/Cargo.toml
[lints]
workspace = true

4.4 Lint Groups 概览

Clippy 将 800+ 条 lint 规则分为以下组别:

组别 描述 默认级别
clippy::all 所有默认启用的 lint(correctness + suspicious + style + complexity + perf) warn/deny
clippy::correctness 明显错误或无用的代码 deny
clippy::suspicious 很可能错误或无用的代码 warn
clippy::style 应采用更符合 Rust 惯用法编写的代码 warn
clippy::complexity 用复杂方式实现简单功能 warn
clippy::perf 可以优化以提高运行速度的代码 warn
clippy::pedantic 较为严格或偶尔误报的 lint allow
clippy::restriction 限制使用某些语言和库特性的 lint(不应整体启用) allow
clippy::nursery 仍在开发中的新 lint 规则 allow
clippy::cargo Cargo 清单(Cargo.toml)相关的 lint allow

注意:restriction 组不应整体启用。其中包含的 lint 可能对完全合理的代码发出警告,甚至可能与其他 lint 相互矛盾。应逐条评估后选择性启用。参考:Lint 分组说明

4.5 各 Lint Group 中的代表性规则

clippy::correctness(默认 deny)

规则 说明
clippy::derivable_impls 检测可以自动 derive 的手动 trait 实现
clippy::dropping_copy_types 检测对 Copy 类型的 drop 调用(无意义操作)
clippy::empty_loop 检测无副作用的无限循环

clippy::perf(默认 warn)

规则 说明
clippy::needless_collect 检测不必要的集合创建(如 .collect() 后仅调用 .len()
clippy::redundant_clone 检测对 Copy 类型的冗余 clone 调用
clippy::large_stack_arrays 检测栈上过大的数组分配
clippy::inefficient_to_string 检测低效的 to_string 调用

clippy::pedantic(默认 allow)

规则 说明
clippy::missing_errors_doc 要求 fallible 函数文档中描述可能的错误
clippy::cast_precision_loss 检测可能导致精度损失的数值类型转换
clippy::similar_names 检测名称过于相似的变量
clippy::wildcard_imports 警告通配符 use 导入(如 use super::*

clippy::restriction(默认 allow,不应整体启用)

规则 说明
clippy::unwrap_used 禁止使用 .unwrap()
clippy::expect_used 禁止使用 .expect()
clippy::panic 禁止使用 panic!
clippy::todo 禁止使用 todo!
clippy::float_arithmetic 禁止浮点算术运算
clippy::indexing_slicing 禁止直接索引和切片操作

完整 lint 规则列表:Clippy Lint 文档

5. 主流集成方式

5.1 Cargo 集成(生态主流)

Clippy 作为 Cargo 的子命令,是 Rust 生态中最主流的集成方式。

安装 Clippy 组件

rustup component add clippy

如果使用 minimal profile 安装的 Rust 工具链,Clippy 不会自动安装,需要手动添加。参考:安装指南

常用 Cargo 命令

# 基础检查(运行默认 lint 组 clippy::all)
cargo clippy

# 检查所有目标(库、二进制、测试、示例、基准测试)
cargo clippy --all-targets

# 检查所有 features 组合
cargo clippy --all-features

# 自动修复可修复的问题(--fix 隐含 --all-targets)
cargo clippy --fix

# 仅检查 Workspace 中的特定 crate
cargo clippy -p crate_name

# 仅检查指定 crate(不含路径依赖)
cargo clippy -p crate_name -- --no-deps

# Workspace 级别检查
cargo clippy --workspace --all-targets

更多用法参考:使用指南

在 Cargo.toml 中配置 lint 级别(Cargo 1.74+ 支持 [lints] section):

# Cargo.toml
[lints.clippy]
all = "warn"
pedantic = "warn"
unwrap_used = "allow"

Workspace 级别统一配置

# Cargo.toml(Workspace 根目录)
[workspace.lints.clippy]
all = "warn"
pedantic = "warn"
unwrap_used = "warn"

[workspace.lints]
workspace = true

# 子 crate 的 Cargo.toml
[lints]
workspace = true

增量检查:Cargo 增量编译。Cargo 本身支持增量编译(incremental compilation),cargo clippy 会自动利用增量编译缓存,仅重新分析发生变更的代码模块及其依赖。对于大型项目,增量编译可以显著减少 Clippy 的分析时间。

# 利用增量编译,仅重新分析变更的模块
cargo clippy --all-targets

5.2 pre-commit 集成

使用 language: system 的本地配置(依赖本地 Rust 工具链):

# .pre-commit-config.yaml
repos:
  - repo: local
    hooks:
      - id: clippy
        name: clippy
        entry: cargo clippy --all-targets -- -D warnings
        language: system
        types: [rust]
        pass_filenames: false # Clippy 需要分析整个 crate,不能只检查单个文件

注意:此配置依赖本地已安装 Rust 工具链和 Clippy 组件(rustup component add clippy)。pass_filenames: false 是必须的,因为 Clippy 以 crate 为单位进行分析,不支持对单个文件独立检查。pre-commit 框架默认仅对暂存区变更文件触发 hook,但由于 Clippy 的特性,实际仍会检查整个 crate。

也可以使用社区维护的 doublify/pre-commit-rust 仓库(该仓库最后更新于 2020 年,建议评估后使用):

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/doublify/pre-commit-rust
    rev: v1.0
    hooks:
      - id: clippy
        args: [--, -D, warnings]

增量检查:当通过 pre-commit local hook 集成 Clippy 时,pre-commit 框架默认只对暂存区中变更的 .rs 文件触发 hook。但由于 Clippy 的 local hook 使用 pass_filenames: false(Clippy 以 crate 为单位分析,不支持单文件检查),pre-commit 只控制"何时触发",实际检查范围由 Cargo 的增量编译决定。

# .pre-commit-config.yaml
- repo: local
  hooks:
    - id: clippy
      name: Clippy
      entry: cargo clippy -- -D warnings
      language: system
      files: \.rs$
      pass_filenames: false # Clippy 以 crate 为单位,不支持单文件

pre-commit 负责"何时触发"(只在有 .rs 文件变更时),Cargo 增量编译负责"加速检查"(仅重新分析变更的代码模块及其依赖)。由于 Clippy 是语义分析工具,无法像文本格式化工具那样只处理单个变更文件,pass_filenames: false 是必须的。CI 中可通过 pre-commit run --all-files 做全量检查。

5.3 IDE 集成

VS Code(rust-analyzer)

rust-analyzer 扩展内置 Clippy 支持,可在编辑时实时显示 Clippy 警告和修复建议。

settings.json 中配置:

{
  "rust-analyzer.checkOnSave.command": "clippy",
  "rust-analyzer.checkOnSave.extraArgs": [
    "--all-targets",
    "--",
    "-W",
    "clippy::pedantic"
  ]
}

配置后,rust-analyzer 会在保存文件时自动运行 Clippy,将警告和错误以内联方式显示在编辑器中。

IntelliJ RustRover

RustRover(原 IntelliJ Rust)内置 Clippy 支持。

配置路径:Preferences > Languages & Frameworks > Rust > External Linter > Clippy

启用后,Clippy 检查结果会实时显示在编辑器和 Problems 面板中。

Vim / Neovim

使用 Neovim LSP 配置,rust-analyzer 会自动集成 Clippy:

-- init.lua(Neovim + rust-analyzer)
vim.lsp.config.rust_analyzer = {
    settings = {
        ["rust-analyzer"] = {
            checkOnSave = {
                command = "clippy",
                extraArgs = { "--all-targets" },
            },
        },
    },
}

5.4 命令行使用方式

# 运行默认 lint 规则(clippy::all 组)
cargo clippy

# 自动修复可修复的问题
cargo clippy --fix

# 将所有警告视为错误(CI 推荐)
cargo clippy -- -D warnings

# 启用 pedantic 组(更严格的检查)
cargo clippy -- -W clippy::pedantic

# 仅启用特定 lint
cargo clippy -- -W clippy::unwrap_used -W clippy::expect_used

# 禁用特定 lint
cargo clippy -- -A clippy::too_many_arguments

# 允许所有默认 lint,仅警告特定 lint
cargo clippy -- -A clippy::all -W clippy::useless_format

# 检查所有目标(含测试、示例、基准测试)
cargo clippy --all-targets -- -D warnings

# 检查所有 features
cargo clippy --all-features -- -D warnings

不使用 Cargo 时,可直接使用 clippy-driver

clippy-driver --edition 2018 -Cpanic=abort foo.rs

注意:clippy-driver 仅用于运行 Clippy 检查,不应作为 rustc 的通用替代品。参考:clippy-driver 用法

增量检查 -- 对于需要精确控制检查范围的高级场景,可以结合 git diff 获取变更文件列表,再通过 --no-deps-p 参数限定检查范围:

# 获取变更的 .rs 文件,提取所属 crate,逐个检查
CHANGED_CRATES=$(git diff --name-only --diff-filter=ACMR HEAD | \
  grep '\.rs$' | \
  xargs -I{} dirname {} | \
  sort -u | \
  while read dir; do
    # 查找包含该文件的 crate
    cargo metadata --no-deps --format-version 1 2>/dev/null | \
      python3 -c "import sys,json; print(' '.join(p['name'] for p in json.load(sys.stdin)['packages'] if any(s.startswith('$dir') for s in p.get('sources',[]))))"
  done | sort -u)

for crate in $CHANGED_CRATES; do
  cargo clippy -p "$crate" -- --no-deps -D warnings
done

不支持的情况:Clippy 原生不支持对单个 .rs 文件进行独立检查。如果需要类似功能,业界主流绕过方案是:

  • 依赖 Cargo 增量编译缓存自动跳过未变更模块
  • 在 CI 中通过 paths 过滤减少触发频率
  • 对于非 Cargo 项目,使用 clippy-driver 对单个文件进行检查(但会缺少 crate 级别的类型信息)

CI 脚本调用

GitHub Actions

GitHub 托管的 runner(latest stable Rust)已预装 Clippy。

# .github/workflows/clippy.yml
name: Clippy

# 确保所有警告(包括 Clippy lints)都会导致 CI 失败
env:
  RUSTFLAGS: "-Dwarnings"

on: [push, pull_request]

jobs:
  clippy_check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - name: Run Clippy
        run: cargo clippy --all-targets --all-features

参考官方文档:GitHub Actions 集成

也可以使用 dtolnay/rust-toolchain@clippy 安装 Clippy 专用工具链:

- uses: dtolnay/rust-toolchain@clippy
- run: cargo clippy -- -Dclippy::all -Dclippy::pedantic

GitLab CI

# .gitlab-ci.yml
variables:
  RUSTFLAGS: "-Dwarnings"

clippy_check:
  image: rust:latest
  script:
    - rustup component add clippy
    - cargo clippy --all-targets --all-features

参考官方文档:GitLab CI 集成

增量检查 -- 在 GitHub Actions 中,可使用 paths 过滤器仅在特定文件变更时触发 Clippy 检查:

# .github/workflows/clippy.yml
on:
  push:
    paths:
      - "**.rs"
      - "Cargo.toml"
      - "Cargo.lock"
      - "clippy.toml"
      - ".clippy.toml"
  pull_request:
    paths:
      - "**.rs"
      - "Cargo.toml"
      - "Cargo.lock"
      - "clippy.toml"
      - ".clippy.toml"

jobs:
  clippy_check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - run: cargo clippy --all-targets --all-features -- -D warnings

6. 告警抑制(屏蔽)方法

Clippy 提供多种灵活的告警抑制方式,从代码级到配置级均可精确控制。

参考官方文档:配置指南 - Allowing/Denying Lints

6.1 通过代码属性屏蔽(Attributes)

在源代码中使用 #[allow]#[warn]#[deny]#[forbid] 属性控制 lint 行为。

参考:Attributes in Code

Crate 级别(作用于整个 crate,使用 #!):

// 允许所有 Clippy 默认警告
#![allow(clippy::all)]

// 启用 pedantic 组的警告
#![warn(clippy::all, clippy::pedantic)]

// 允许 pedantic 组中的特定规则
#![allow(clippy::missing_errors_doc)]

函数/模块级别(使用 #):

// 允许当前函数使用 unwrap
#[allow(clippy::unwrap_used)]
fn critical_operation() {
    let data = get_data().unwrap();
}

// 对特定代码块应用规则
#[deny(clippy::single_match)]
fn example() {
    match result {
        Ok(val) => handle_ok(val),
        Err(_) => {}
    }
}

行内级别

let value = unsafe { transmute::<i32, f32>(x) }; // #[allow(clippy::cast_transmute)]

Lint 级别说明

级别 说明
allow 抑制该 lint,不报错、不警告
warn 检测到问题时输出警告(默认级别)
deny 检测到问题时视为错误,阻止编译
forbid 比 deny 更严格,无法被内层代码属性覆盖

参考:Rustc Lint Levels

6.2 通过命令行参数屏蔽

通过 -A(allow)、-W(warn)、-D(deny)标志在运行时控制 lint。

参考:Command Line Flags

# 允许特定 lint
cargo clippy -- -A clippy::unwrap_used

# 警告特定 lint
cargo clippy -- -W clippy::missing_docs

# 启用 pedantic 组并拒绝特定规则
cargo clippy -- -W clippy::pedantic -D clippy::unwrap_used

# 允许所有默认 lint,仅警告特定 lint
cargo clippy -- -A clippy::all -W clippy::useless_format

# CI 中将所有警告视为错误
cargo clippy -- -D warnings

6.3 通过 Cargo.toml 的 [lints] Section 屏蔽

Cargo.toml 中持久化配置 lint 级别(Cargo 1.74+)。

参考:Lints Section in Cargo.toml | Cargo 官方文档

# Cargo.toml
[lints.clippy]
# 启用所有默认规则
all = "warn"
# 启用 pedantic 组
pedantic = "warn"
# 允许特定规则
unwrap_used = "allow"
# 拒绝特定规则
enum_glob_use = "deny"

6.4 通过工具配置文件屏蔽(clippy.toml)

通过 clippy.toml 配置文件调整 lint 行为参数,如禁用对测试代码的检查、设置 MSRV 等。

参考:配置指南 | Lint 配置项完整列表

# clippy.toml

# 在测试中允许 dbg! 宏
allow-dbg-in-tests = true

# 在测试中允许 unwrap()
allow-unwrap-in-tests = true

# 在测试中允许 expect()
allow-expect-in-tests = true

# 在测试中允许 print 宏
allow-print-in-tests = true

# 指定 MSRV,禁用与当前 Rust 版本不兼容的 lint
msrv = "1.70.0"

6.5 通过条件编译完全跳过 Clippy 分析

在极少数场景下,如果其他抑制方式不够,可通过条件编译完全阻止 Clippy 分析某段代码。

参考:Disabling evaluation of certain code

#![allow(unused)]
fn main() {
    // Clippy 分析时使用 stub,非 Clippy 编译时包含实际代码
    #[cfg(not(clippy))]
    include!(concat!(env!("OUT_DIR"), "/my_big_function-generated.rs"));

    #[cfg(clippy)]
    fn my_big_function(_input: &str) -> Option<MyStruct> {
        None
    }
}

6.6 通过环境变量屏蔽提示信息

通过 CLIPPY_DISABLE_DOCS_LINKS 环境变量禁用 "for further information visit lint-link" 提示信息:

CLIPPY_DISABLE_DOCS_LINKS=1 cargo clippy


← 返回目录 > ← 返回总览