Sub topic 3
Applying Suggested Fixes with Clippy
Assume you know basic Rust syntax, ownership, Cargo projects, terminals, and editors. This chapter focuses on applying Clippy suggestions safely and enforcing the same checks across a project.
Applying Suggested Fixes Automatically
Clippy reports warnings and often provides machine-applicable suggestions. Run the strict check first:
cargo clippy --all-targets --all-features -- -D warningsTo apply suggestions automatically, use:
cargo clippy --fix --allow-dirtyClippy may change source files. Review the diff before committing. Some suggestions change behavior or encode a style preference, so automatic fixes still require judgment.
Tuning Clippy with `clippy.toml`
A clippy.toml file configures Clippy for the project. For example:
msrv = "1.70"
too-many-arguments-threshold = 8The msrv setting is the minimum supported Rust version. It prevents Clippy from recommending APIs unavailable on that version. Threshold settings adjust when a lint becomes useful for your codebase.
Project-Wide Lint Policy in `Cargo.toml`
The [lints.clippy] table records lint levels in version control:
[lints.clippy]
pedantic = { level = "warn", priority = -1 }
unwrap_used = "warn"
module_name_repetitions = "allow"Here, pedantic lints produce warnings, unwrap_used is explicitly checked, and one noisy lint is allowed. A priority of -1 lets individual entries override the group setting.
Enforcing Checks in CI
Run formatting in check mode and make Clippy warnings fail the build:
- run: cargo fmt --all -- --check
- run: cargo clippy --all-targets --all-features -- -D warningsEditor Integration
rust-analyzer can format files on save and display Clippy diagnostics inline. Enable these features in your editor settings, then use CI as the final authority. Editor settings improve feedback speed, while CI keeps checks consistent for every contributor.
Exercise
Which command applies Clippy's machine-applicable suggestions, and what should you do afterward?
Show answer
Run cargo clippy --fix --allow-dirty, inspect the diff, and run the tests.